gpt4 book ai didi

sql - (一张表)获取没有联合的行

转载 作者:行者123 更新时间:2023-11-29 12:07:16 25 4
gpt4 key购买 nike

对不起标题我只是不知道如何简单地解释我想要实现的目标。但其实很简单。

我有下表egr:

+---------+------------+
| offid | groupid |
+---------+------------+
| 1 | 101 |
| 1 | 202 |
| 2 | 202 |
| 2 | 404 |
+---------+------------+

我想获取 groupid 未链接到其他 offid 的行。结果将是:

+---------+------------+
| offid | groupid |
+---------+------------+
| 1 | 101 |
| 2 | 404 |
+---------+------------+

这行得通,但我想知道是否有更优雅的方法来做到这一点?

select * from egr as egr1
where egr1.offid = 1
and egr1.groupid not in (select groupid from egr as egr2 where egr2.offid = 2 and egr1.groupid = egr2.groupid)
union
select * from egr as egr1
where egr1.offid = 2
and egr1.groupid not in (select groupid from egr as egr2 where egr2.offid = 1 and egr1.groupid = egr2.groupid)

如果您想尝试:

create table egr (offid int, groupid int);
insert into egr values (1, 101), (1, 202), (2, 202), (2, 404);

谢谢

最佳答案

这是你想要的吗?

select e.*
from egr e
where not exists (select 1
from egr e2
where e2.groupid = e.groupid and e2.offid <> e.offid
);

或者,如果您只想限制这两个报价:

select e.*
from egr e
where e.offid in (1, 2) and
not exists (select 1
from egr e2
where e2.groupid = e.groupid and
e2.offid in (1, 2) and
e2.offid <> e.offid
);

关于sql - (一张表)获取没有联合的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56246041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com