我有一个类似这样的表,我需要在其中过滤关键字并检索关键字列表。
id key
1 1
1 2
1 3
1 4
2 1
2 3
3 1
3 4
4 1
4 4所需输出:
id key
2 1
2 3
3 1
3 4这里我想得到一个id列表,即(2,3),其中键1存在,而键2缺失。
发布于 2017-06-29 23:57:33
这回答了被问到的问题:“这里我想获得一个id列表……其中键1存在,键2缺失。”
您可以使用exists和not exists
select t.*
from t
where exists (select 1 from t t2 where t2.id = t.id and t2.key = 1) and
not exists (select 1 from t t2 where t2.id = t.id and t2.key = 2);如果您只需要ids,那么我更喜欢聚合和having
select id
from t
group by id
having sum(case when key = 1 then 1 else 0 end) > 0 and
sum(case when key = 2 then 1 else 0 end) = 0;发布于 2017-06-30 00:21:21
假设您的表名为‘the’,那么根据您提到的输出,sql查询将是
SELECT * FROM testing WHERE key !=2,id in (2,3)
https://stackoverflow.com/questions/44829854
复制相似问题