Use not exists
. To bring france
rows that do not exist in any of the 3 other tables:
select id
from france f
where not exists (select 1 canada c where c.id = f.id)
and not exists (select 1 cameroon c where c.id = f.id)
and not exists (select 1 gabon g where g.id = f.id)
If you want to search all tables at once for id
s that do not exists in any other, a more generic approach uses union all
and aggregation:
select id, min(who) who
from (
select 'france' who, id from france
union all select 'canada', id from canada
union all select 'cameroon', id from cameroon
union all select 'gabon', id from gabon
) t
group by id
having count(*) = 1
If a single table may contain duplicate id, you can change the having
clause to:
having min(who) = max(who)
CLICK HERE to find out more related problems solutions.