Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to put one left outer join within other left outer join

Can I put a left outer join inside another left outer join? Like this:

SELECT * FROM table1 
LEFT OUTER JOIN table2 ON (LEFT OUTER JOIN table 3 ON (Join Conditions))
WHERE
....(where conditions)
like image 311
Sunil luitel Avatar asked May 01 '12 11:05

Sunil luitel


People also ask

Can you do two left outer JOINs?

Yes, it is possible. We would use a query with two LEFT OUTER JOINs to retrieve the hierarchy.

Can you mix JOINs in SQL?

An SQL query can JOIN multiple tables. For each new table an extra JOIN condition is added.

Is left outer join and left join same?

There really is no difference between a LEFT JOIN and a LEFT OUTER JOIN. Both versions of the syntax will produce the exact same result in PL/SQL. Some people do recommend including outer in a LEFT JOIN clause so it's clear that you're creating an outer join, but that's entirely optional.

Can we use left outer join and inner join together?

The LEFT OUTER join will retrieve all rows from the table on the left of the join whether they match or not. In the subsequent INNER JOIN, obviously if something doesn't match up, you will lose some rows.


1 Answers

To group multiple joins, the syntax is as follows (untested on db2)

SELECT *
FROM table1 t1
LEFT JOIN (
  table2 t2 INNER JOIN table3 t3 ON t3.someId = t2.someId
) ON t2.someId = t1.someId

Same syntax for left join inside LEFT JOIN(), but please read comment by @X-Zero

SELECT *
FROM table1 t1
LEFT JOIN (
  table2 t2 LEFT JOIN table3 t3 ON t3.someId = t2.someId
) ON t2.someId = t1.someId
like image 156
Chris Gessler Avatar answered Nov 15 '22 18:11

Chris Gessler