如何检索包含和排除特定键的列表?
how to retrieve a list including and excluding a particular key?
我有一个像这样的 table,我需要过滤键并检索键列表。
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。
这回答了问题 "Here i want to get a list of id . . . in which key 1 is present and key 2 is missing."
您可以使用 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);
如果你只想要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;
假设您的 table 名称是 'testing' 那么根据您提到的输出,sql 查询将是
SELECT *
来自 testing
WHERE key
!=2 and id in (2,3)
我有一个像这样的 table,我需要过滤键并检索键列表。
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。
这回答了问题 "Here i want to get a list of id . . . in which key 1 is present and key 2 is missing."
您可以使用 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);
如果你只想要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;
假设您的 table 名称是 'testing' 那么根据您提到的输出,sql 查询将是
SELECT *
来自 testing
WHERE key
!=2 and id in (2,3)