我的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
谢谢您的时间:))
答案 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_id
是int
,您可以这样做:
SELECT groups_id
FROM members
GROUP BY groups_id
HAVING MIN(users_id) = 1 AND MAX(users_id) = 2;
这将选择具有两个相关groups_id
值,users_id
和1
的{{1}}值。
修改强>
对于任何两个2
值,您可以使用以下查询:
user_id