SQL:如何获取仅包含某些ID的行?

时间:2013-11-17 20:01:05

标签: mysql sql database relational-division

我有下表:

+--------+--------+
|  group |  user  |
+--------+--------+
|      1 |      1 |
|      1 |      2 |
|      2 |      1 |
|      2 |      2 |
|      2 |      3 |
+--------+--------+

我需要选择包含用户1和2以及 1和2(不是3或42)的组。

我试过

SELECT `group` FROM `myTable` 
WHERE `user` = 1 OR `user` = 2 
GROUP BY `group`;

但那当然给了我第1组和第2组,而第2组也包含了用户3。

2 个答案:

答案 0 :(得分:2)

单程

SELECT `group` 
FROM myTable
GROUP BY `group`
HAVING GROUP_CONCAT(DISTINCT `user` ORDER BY `user`) = '1,2';

SQL Fiddle

答案 1 :(得分:1)

你可以试试这个:

SELECT `group` 
FROM myTable
GROUP BY `group`
HAVING GROUP_CONCAT(DISTINCT `user` ORDER BY `user`) = '1,2';