-2

So I have a table kind of like the one below.

+----+----------+---------+
| ID | group_id | user_id |
+----+----------+---------+
|  1 |       10 |       9 |
|  2 |       20 |       8 |
|  3 |       10 |       7 |
|  4 |       10 |       6 |
|  5 |       20 |       5 |
+----+----------+---------+

I have an array of user IDs [9,7,6] and I'd like to get the Group ID where all the IDs are in the same group?

My current query:

SELECT group_id FROM group_user WHERE user_id IN (9,7,6) GROUP BY group_id

Bare in mind I'm not overly familiar with SQL queries.

Thanks


EDIT

I have opened a new question with more detail and my goal.

SQL, check if conversation exists between group


Community
  • 1
  • 1
Levi Cole
  • 3,561
  • 1
  • 21
  • 36

3 Answers3

1

You can use conditional aggregation to find group_id's which have the required user_id's associated with them.

SELECT group_id 
FROM group_user 
group by group_id
having sum(case when user_id IN (9,7,6) then 1 else 0 end) = 3
Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
0

Your query should be:

SELECT DISTINCT(group_id) FROM group_user WHERE user_id IN (9,7,6)
William Perron
  • 485
  • 7
  • 16
0
SELECT group_id 
FROM group_user 
WHERE user_id IN (9,7,6) 
GROUP BY group_id
HAVING count(DISTINCT user_id) = 3
AND count(DISTINCT group_id) = 1

makes sure that all 3 ids are in the same group_id and that they're not in any other group.

http://sqlfiddle.com/#!9/540f96/2

Tin Tran
  • 6,194
  • 3
  • 19
  • 34