How to create sql query to select the distinct table A data
as in the image
Thanks
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
.
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 aLEFT JOIN
: Optionally get the matching rows from b and c as wellWHERE
: In fact, no. Keep only those rows from a, for which there was no match in b and cUsing 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.
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.
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)
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