从包含指定成员的表中选择组ID

时间:2016-03-30 19:21:24

标签: mysql

我的members表格中有以下示例数据:

+----+----------+-----------+  
| id | users_id | groups_id |  
+----+----------+-----------+  
|  1 |        1 |         1 |  
|  2 |        2 |         1 |  
|  3 |        1 |         2 |  
|  4 |        2 |         2 |  
|  5 |        3 |         2 |  
+----+----------+-----------+  

我想选择groups_id,其中包含两个指定的成员,例如1和2.我尝试使用此查询:

SELECT groups_id 
FROM   members 
WHERE  users_id IN ( 2, 1 ) 
GROUP  BY groups_id 
HAVING Count(users_id) = 2; 

但它仍会返回groups_id 1和2 谢谢您的时间:))

2 个答案:

答案 0 :(得分:1)

使用条件计数

因此,群组中有一个1和一个2

<强> SQL Fiddle Demo

SELECT groups_id 
FROM   members 
GROUP  BY groups_id 
HAVING COUNT(CASE WHEN users_id = 1 THEN 1 END) = 1
   AND COUNT(CASE WHEN users_id = 2 THEN 1 END) = 1 
   AND COUNT(*) = 2;

答案 1 :(得分:1)

如果users_idint,您可以这样做:

SELECT groups_id 
FROM   members 
GROUP  BY groups_id 
HAVING MIN(users_id) = 1 AND MAX(users_id) = 2;

这将选择具有两个相关groups_id值,users_id1的{​​{1}}值。

Demo here

修改

对于任何两个2值,您可以使用以下查询:

user_id