I'm putting together a threaded messaging service and I am trying to wrap my head a round a particular query. I am currently trying to create a procedure which will return the thread_id when provided an array of user_ids.
There are only two columns in the table: thread_id & user_id. I have 4 rows in the table for testing:
INSERT INTO thread_users (`thread_id`, `user_id`) VALUES (1,1);
INSERT INTO thread_users (`thread_id`, `user_id`) VALUES (1,70);
INSERT INTO thread_users (`thread_id`, `user_id`) VALUES (2,1);
INSERT INTO thread_users (`thread_id`, `user_id`) VALUES (2,21);
This examples user 1 messaging user 70 to start the first thread and then messages user 21 to start thread 2;
Since I already have the ids of both users what I am trying to derive is finding the the thread_id based on the list of users "subscribed" to the thread.
SELECT participants.*
FROM (
SELECT DISTINCT `thread_id`
FROM `thread_users`
WHERE `thread_users`.`user_id` IN (1, 21)
GROUP BY `thread_id`
) AS participants
There is going to be more data requested through a couple of joins, although I don't want to include it into this question... So, with that said, lets just shorten the query to:
SELECT DISTINCT `thread_id`
FROM `thread_participants`
WHERE `thread_participants`.`user_id` IN (1, 21)
GROUP BY `thread_id`
Of which should return 2.
I recognize that this query should return the proper thread_id wither if there is 2 users associated to a thread or 20. Any help would greatly appreciated:-) Thank You!