[英]SQL: How can I select rows from a table that aren't in another one using group by?
Suppose that I have a table A with a column id (PK) and a table B with a foreign key to_id that refers to id.假设我有一个带有列 id (PK) 的表 A 和一个带有引用 id 的外键 to_id 的表 B。
I want to select all rows from A that aren't refered from B.我想从 A 中选择所有未从 B 引用的行。
I thought about the following approach:我想到了以下方法:
select * from A group by id having id not in (select to_id from B);
But I'd like to know if there is an approach that doens't use "NOT IN".但我想知道是否有一种不使用“NOT IN”的方法。
Something like:就像是:
select * from A, B group by id having id = to_id and count(to_id) = 0;
This one doesn't work, but I'd like something like this if possible.这个不起作用,但如果可能的话,我想要这样的东西。
I want to select all rows from A that aren't refered from B.我想从 A 中选择所有未从 B 引用的行。
This reads like not exists
:这读起来就像not exists
:
select a.*
from a
where not exists (select 1 from b where b.to_id = a.id)
There is no need to group by
whatsoever.没有必要以任何方式group by
。
Another typical approach is an anti- left join
:另一种典型的方法是反left join
:
select a.*
from a
left join b on b.to_id = a.id
where b.to_id is null
Just a left join and a where condition to pull only those which have a null as the b id.只是一个左连接和一个 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.