Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join multiple select statements in SQL

I would like to know how a query of this form could be improved on in terms of 1) Style and 2) Performance. In case it matters, I'm using Oracle as my database. Also, the purpose of this query is to select all records from the first select statement that do not have a corresponding record in the set of records to the right of the LEFT JOIN. The records from ColumnA are not necessarily unique in any of the tables.

select ColumnA
from
    (Select ColumnA
    from Table1)
left join
    ((select ColumnA, ColumnB
    from Table2)
    union
    (select ColumnA, ColumnB
    from Table3))
using (ColumnA)
where ColumnB is null
group by ColumnA;

Thank you.

like image 625
Eduardo Avatar asked Feb 17 '23 01:02

Eduardo


2 Answers

I think you could rewrite this query to the following (see this SQL Fiddle):

SELECT  DISTINCT ColumnA
FROM    (SELECT  ColumnA
         FROM    Table1)

MINUS

(SELECT  ColumnA
FROM    Table2
UNION
SELECT  ColumnA
FROM    Table3);

As for style, I'd recommend using the explicit join condition syntax LEFT JOIN ... ON table1.somecolumn = table2.someothercolumn instead of the USING condition, for readability and clarity. But this might well be personal preference :-)

like image 87
Josien Avatar answered Feb 28 '23 04:02

Josien


I don't see the need for the UNION:

select T1.ColumnA
from Table1 T1
    left join Table2 T2 ON T1.ColumnA = T2.ColumnA
    left join Table3 T3 ON T1.ColumnA = T3.ColumnA
where T2.ColumnA IS NULL 
    or T3.ColumnA IS NULL
group by T1.ColumnA;

Another option would be to use NOT IN:

select distinct ColumnA
from Table1 
where ColumnA not in (select ColumnA from Table2) 
    and ColumnA not in (select ColumnA from Table3);

Both of these should return any ColumnA records in Table1 that aren't in Table2 or Table3.

like image 30
sgeddes Avatar answered Feb 28 '23 03:02

sgeddes