Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Full Outer Joins

Tags:

sql

impala

I want to use the result of a FULL OUTER JOIN as a table to FULL OUTER JOIN on another table. What is the syntax that I should be using?

For eg: T1, T2, T3 are my tables with columns id, name. I need something like:

T1 FULL OUTER JOIN T2 on T1.id = T2.id   ==> Let this be named X

X FULL OUTER JOIN T3 on X.id = t3.id  

I want this to be achieved so that in the final ON clause, I want the T3.id to match either T1.id or T2.id. Any alternative way to do this is also OK.

like image 244
Abhishek Avatar asked Mar 08 '16 11:03

Abhishek


2 Answers

SELECT COALESCE(X.id,t3.id) AS id, *-- specific columns here instead of the *
FROM 
    (
       SELECT COALESCE(t1.id,t2.id) AS id, * -- specific columns here instead of the *
       FROM T1 FULL OUTER JOIN T2 on T1.id = T2.id
    ) AS X
    FULL OUTER JOIN T3 on X.id = t3.id
like image 108
TT. Avatar answered Oct 29 '22 23:10

TT.


Often, chains of full outer joins don't behave quite as expected. One replacements uses left join. This works best when a table has all the ids you need. But you can also construct that:

from (select id from t1 union
      select id from t2 union
      select id from t3
     ) ids left join
     t1
     on ids.id = t1.id left join
     t2
     on ids.id = t2.id left join
     t3
     on ids.id = t3.id

Note that the first subquery can often be replaced by a table. If you have such a table, you can select the matching rows in the where clause:

from ids left join
     t1
     on ids.id = t1.id left join
     t2
     on ids.id = t2.id left join
     t3
     on ids.id = t3.id
where t1.id is not null or t2.id is not null or t3.id is not null
like image 23
Gordon Linoff Avatar answered Oct 29 '22 23:10

Gordon Linoff