Question

I am currently trying to implement a messaging system using mysql. My schema thus far consists of the tables: threads, thread_user, messages, message_read as detailed in thread messaging system database schema design. I require the number of threads to which a user belongs but to which it is not only the user that has posted. I can firstly find a list of threads to which a user belongs with the query:

SELECT threads.id
FROM threads INNER JOIN thread_user ON thread_user.thread_id = threads.id
WHERE thread_user.user_id = 1
AND threads.draft = false

I can then find a list of threads to which users other than the main user have posted using:

SELECT threads.id
FROM threads INNER JOIN messages ON messages.thread_id = threads.id
WHERE messages.user_id != 1

Threads must have at least one message so by then finding the intersection between these two subqueries I can find a list of threads to which the user belongs and to which it is not just the user who has posted.

For example were the first query which shows the threads to which the user belongs to return 3, 7, 10, 12 and the second query which shows a list of threads to which users other than the main user have posted to return amongst others 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. Then using the intersection of the two sets we could determine that threads 3 and 7 were threads which the user belonged and to which it is not just the user who has posted to the thread.

Is there a way of doing this intersection within the mysql query itself?

Thanks in advance, Ben

Was it helpful?

Solution

Just try this query:

SELECT threads.id
FROM threads 
INNER JOIN thread_user ON thread_user.thread_id = threads.id
INNER JOIN messages ON messages.thread_id = threads.id
WHERE thread_user.user_id = 1
AND threads.draft = false
AND messages.user_id != 1

INNER JOIN give you the intersection between two table based 'ON' your condition "thread_user.thread_id = threads.id"

your 1st query give u the intersection between threads, and thread_user --> as table_1 and your 2nd one give u the intersection between threads, and messages --> as table_2

what I done is simply getting the intersection between messages, and table_1 -which is the intersection between threads, and thread_user-

and I collect your conditions from the two queries, and add it to the new query.

OTHER TIPS

In this particular case you can just use one query with 2 INNER JOIN like this:

SELECT 
  threads.id
FROM threads 
INNER JOIN thread_user ON thread_user.thread_id = threads.id AND thread_user.user_id = 1
INNER JOIN messages ON messages.thread_id = threads.id AND messages.user_id != 1
WHERE threads.draft = false

Thus the inner join will "kind of" do the intersection for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top