Here is a scenario where we wanna retrieve the specific GroupId no. Eg., 6 having only 3 users say UserId's with 2, 1, 3 with that specific Group
This is the query I tried to execute
SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3) AND userid IN (1, 2, 3);
SQL Fiddle DEMO
Below are the details from the above query which had been broken into pieces
SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3
group_id
5
6
SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3)
group_id
5
5
5
6
6
6
SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3) AND userid IN (1, 2, 3)
group_id
5
5
6
6
6
SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3) AND userid=1 AND userid=2 and userid = 3
group_id
NULL
Expected Result:
group_id
6
Since there is only one group with group_id = 6 having 3 users with unique userid = 1, 2, 3
So that group_id = 6 must be retrieved at the end result!