I have a simple message schema where a “thread” ties 2 or more users to a stream of messages. Each message belongs to a single thread. It works just like SMS messages, or Facebook messages.
Given a string (representing a name or partial name of a user), I need a query that will find all threads that match where:
- the current user (userID) is a member of the thread
- the name or partial name of a user is also a member of the thread
Here are my tables:
MessageThreads:
threadID
lastUpdated
MessageThreadUsers:
threadFK
userFK
Users
userID
userFirstName
userLastName
userFullName
This query gets all threads that the current user belongs to:
SELECT DISTINCT threadFK FROM MessageThreadUsers
WHERE userFK = 'usr_developer'
But how would I join each thread with all users in the thread (not including the current user) that match by name or partial name?
This should show you the other users of all threads that the ‘usr_developer’ key is part of.
This joins against the tables twice, first, we join to the users table to only pull back the set of threads that have a user with the id of ‘usr_developer’. Then we join the resulting threads against the users table again, this time where the user id is not usr_developer. Finally we can filter the result set by the name.