sql查询选择没有的记录

时间:2018-03-21 13:30:48

标签: sql having

我在编写SQL查询时遇到了困难 返回我没有typeA记录的ID 例如

ID | type
1  | typeA
1  | typeB
1  | typeC
2  | typeB
2  | typeC
3  | typeB

此查询应返回ID 2和3

提前感谢任何建议 扬

2 个答案:

答案 0 :(得分:2)

您可以使用:

select id
from t
group by id
having sum(case when type = 'TypeA' then 1 else 0 end) = 0;

在许多数据库中,您还可以使用except / minus

select id
from t
except  -- or minus
select id
from t
where type = 'TypeA';

答案 1 :(得分:2)

试试这个:

SELECT t1.id
FROM   t t1
WHERE  t1.id NOT IN (SELECT DISTINCT t2.id FROM t t2 WHERE t2.type = 'typeA');