对不起,我只是不知道如何简短地解释我想要达到的目标。但这实际上很简单。
我有下表egr:
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 );