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.
I want to select all rows from A that aren't refered from 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".
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.
This reads like 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.
Another typical approach is an anti- 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.
select a.*
from a
left join b on b.to_id = a.id
where b.to_id is null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.