0

How to create sql query to select the distinct table A data as in the image image

Thanks

4 Answers4

6

One method is minus:

select . . .
from a
minus
select . . .
from b
minus
select . . .
from c;

Or, not exists:

select a.*
from a
where not exists (select 1 from b where . . . ) and
      not exists (select 1 from c where . . . );

You don't clarify what the matching conditions are, so I've used . . . for generality.

These two versions are not the same. The first returns unique combinations of columns from a where those same columns are not in b or c. The second returns all columns from a, where another set is not in b or c.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
6

If you must use LEFT JOIN to implement what is really an anti join, then do this:

SELECT *
FROM a
LEFT JOIN b ON b.a_id = a.a_id
LEFT JOIN c ON c.a_id = a.a_id
WHERE b.a_id IS NULL
AND c.a_id IS NULL

This reads:

  • FROM: Get all rows from a
  • LEFT JOIN: Optionally get the matching rows from b and c as well
  • WHERE: In fact, no. Keep only those rows from a, for which there was no match in b and c

Using NOT EXISTS() is a more elegant way to run an anti-join, though. I tend to not recommend NOT IN() because of the delicate implications around three valued logic - which can lead to not getting any results at all.

Side note on using Venn diagrams for joins

A lot of people like using Venn diagrams to illustrate joins. I think this is a bad habit, Venn diagrams model set operations (like UNION, INTERSECT, or in your case EXCEPT / MINUS) very well. Joins are filtered cross products, which is an entirely different kind of operation. I've blogged about it here.

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
1

Select what isn't in B nor C nor in A inner join B inner join C

Select * from A
where A.id not in ( select coalesce(b.id,c.id) AS ID
                    from b full outer join c on (b.id=c.id) )

or also: --- you don't need a join so jou can avoid doing it

select * from A
where a.id not in (select coalesce (B.ID,C.ID) AS ID from B,C)
DDS
  • 2,340
  • 16
  • 34
  • No, in a join, at least b.id or c.id exists so i'm sure at least one value exixts (I assume ID field is not null) – DDS May 28 '18 at 11:16
0

I would do like this:

SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL

Someone already ask something related to your question, you should see it here