sql查询select条没有的记录
sql query select records that not having
我在编写 SQL 查询时遇到困难
那 return 是没有 typeA 记录的我的 ID
例如
ID | type
1 | typeA
1 | typeB
1 | typeC
2 | typeB
2 | typeC
3 | typeB
此查询应 return ID 2 和 3
提前感谢您的任何建议
一月
您可以使用:
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';
试试这个:
SELECT t1.id
FROM t t1
WHERE t1.id NOT IN (SELECT DISTINCT t2.id FROM t t2 WHERE t2.type = 'typeA');
我在编写 SQL 查询时遇到困难 那 return 是没有 typeA 记录的我的 ID 例如
ID | type
1 | typeA
1 | typeB
1 | typeC
2 | typeB
2 | typeC
3 | typeB
此查询应 return ID 2 和 3
提前感谢您的任何建议
一月
您可以使用:
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';
试试这个:
SELECT t1.id
FROM t t1
WHERE t1.id NOT IN (SELECT DISTINCT t2.id FROM t t2 WHERE t2.type = 'typeA');