如何检索列表,包括和排除特定键



我有一个表格,我需要在键上过滤并检索键的列表。

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。

这回答了所问的问题:"这里我想获取一个键1的列表,其中键1丢失,键2丢失。"

您可以使用existsnot 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);

如果您只想要ID,那么我更喜欢聚合和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;

假设您的表名称是'测试',然后根据您提到的输出,SQL查询将为

选择 *来自testing其中 key!= 2和(2,3(

中的ID

最新更新