我有很多关系
code1 code2
1 10 <-- Desired (1 appears more than once)
1 11 <-- Desired (1 appears more than once)
1 17 <-- Desired (1 appears more than once)
2 10
3 11 <-- Desired (3 appears more than once)
3 17 <-- Desired (3 appears more than once)
4 10
5 10
...我想写一个单个SQL查询,结果如下:
code1
1 <-- This result appears because 1 appears more than once above
3 <-- This result appears because 3 appears more than once above
(即,单个SQL查询返回code1
中与11和17绑定的所有行的所有行)...
我可以写什么SQL?有可能吗?
答案 0 :(得分:3)
您可以使用GROUP BY和HAVING来过滤掉这些内容。试试这个:
SELECT code1
FROM myTable
GROUP BY code1
HAVING COUNT(*) > 1;
这将通过对所有“code1”值进行分组,并查看哪些组具有多行来拉出所有“code1”值。
修改强>
如果要在其他列中包含条件,可以先编写一个只获取所需行的查询(正如您在注释中所说,其中code2等于11或17),如下所示:
SELECT code1, code2
FROM myTable
WHERE code2 = 11 OR code2 = 17;
然后,您可以对该查询应用上述过滤器。结果集中不需要code2:
SELECT code1
FROM myTable
WHERE code2 = 11 OR code2 = 17
GROUP BY code1
HAVING COUNT(*) > 1;
我在SQL Fiddle中对此进行了测试,但确实有效。