id string id2
1 a 1
2 b 1
3 a 2
4 c 2
5 d 3
好的,所以我可以得到SELECT * FROM table WHERE string NOT IN ('a','c')
:
2 b 1
5 d 3
但我也希望不能获得包含具有相同id2的a或c的其余行。结果:
5 d 3
你可以使用not exists
:
select t.*
from t
where not exists (select 1
from t t2
where t2.id2 = t.id2 and t2.string in ('A', 'C')
);
如果您只想要id2
值,您可能会发现聚合方便:
select id2
from t
group by id2
having sum(case when string in ('A', 'C') then 1 else 0 end) = 0;
有一个子查询返回带有a或c的id2值。 NOT IN
那些id2值。
SELECT * FROM table
WHERE id2 not in (select id2 from table where string IN ('a','c'))
如果id2可以包含空值,请改为使用NOT EXISTS
:
SELECT * FROM table t1
WHERE NOT EXISTS (select 1 from table t2
where t2.string IN ('a','c')
and t1.id2 = t2.id2))