I’d like to perform a SQL join for the grey painted region of the following Venn diagram, but using no UNIONs:
Please, is it possible?
For the sake of simplicity, think all tables with only two columns: id and value, id is the same for all of them.
Here’s a sample data:
x
Set A
| id | value |
----------------
| 1 | red |
| 2 | magenta |
| 3 | white |
| 4 | yellow |
Set B
| id | value |
----------------
| 2 | magenta |
| 3 | white |
| 5 | blue |
| 6 | cyan |
Set C
| id | value |
----------------
| 7 | green |
| 3 | white |
| 4 | yellow |
| 6 | cyan |
Resulting set
| id | value |
----------------
| 2 | magenta |
| 3 | white |
| 4 | yellow |
| 6 | cyan |
Advertisement
Answer
You can full join
twice and add conditional logic in the where
clause:
select id
from a
full join b using(id)
full join c using(id)
where
case when a.id is not null then 1 else 0 end
+ case when b.id is not null then 1 else 0 end
+ case when c.id is not null then 1 else 0 end
> 1
Not all databases support that syntax. A more widely supported approach is indeed to use union all
and aggregation:
select id
from (
select id from a
union all select id from b
union all select id from c
) t
group by id
having count(*) > 1