Q:

Find single parent id containing exactly two given children

I have a thread table whose id is foreign key column to thread_members table as thread_id. 
Thread to thread_members has one to many relation. 
If thread members given are 5 and 55, I have to find thread which contains only 5 and 55 but there can be many threads containing 5,55 and other members but only one having 5 and 55. 
How can i achieve this in MySQL.

A:

You can use the HAVING clause:
SELECT thread_id
FROM thread_members
GROUP BY thread_id
HAVING COUNT(*) = 2
AND    COUNT(CASE WHEN user_id IN (5, 55) THEN 1 END) = 2

The above returns threads that contain exactly two members, 5 and 55. It assumes that your data does not contain duplicate thread_id, user_id pairs.

