我脑子里似乎很简单,但我无法获得我需要的结果。
我的表
id, code, type
1 1111 1
2 1111 2
3 1222 1 <--- This one
4 1333 1
5 1333 2
6 1444 3 <--- Different type then the others
我希望没有匹配代码的输出与类型2但只查找类型为1或类型2的输出(如果有意义的话)
id, code, type
3 1222 1
注意:我有超过100万条记录要查询,所以我需要快速的东西。
提前致谢。
答案 0 :(得分:1)
SELECT * FROM codes NATURAL JOIN (
SELECT code
FROM codes
WHERE type IN (1,2)
GROUP BY code
HAVING COUNT(DISTINCT type) = 1
) t
在sqlfiddle上查看。
答案 1 :(得分:1)
以下是使用not exists
的解决方案:
SELECT c.*
FROM codes c
WHERE c.type = 1 and
not exists (select 1
from codes c2
where c2.code = c.code and
c2.type = 2
)