[英]SQL: How can I select rows from a table that aren't in another one using group by?
假设我有一个带有列 id (PK) 的表 A 和一个带有引用 id 的外键 to_id 的表 B。
我想从 A 中选择所有未从 B 引用的行。
我想到了以下方法:
select * from A group by id having id not in (select to_id from B);
但我想知道是否有一种不使用“NOT IN”的方法。
就像是:
select * from A, B group by id having id = to_id and count(to_id) = 0;
这个不起作用,但如果可能的话,我想要这样的东西。
我想从 A 中选择所有未从 B 引用的行。
这读起来就像not exists
:
select a.*
from a
where not exists (select 1 from b where b.to_id = a.id)
没有必要以任何方式group by
。
另一种典型的方法是反left join
:
select a.*
from a
left join b on b.to_id = a.id
where b.to_id is null
只是一个左连接和一个 where 条件,只提取那些以 null 作为 b id 的条件。
select a.*
from a
left join b on b.to_id = a.id
where b.to_id is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.