Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

left join and group of inner join

Say, I have the following query:

SELECT * FROM TABLE1 
    JOIN TABLE2 ON ...
    LEFT JOIN TABLE3 ON ...
        JOIN TABLE3_1 ON ...
        JOIN TABLE3_2 ON ...
        JOIN TABLE3_3 ON ...

What I want to achieve is for TABLE3, TABLE3_1, TABLE3_2, TABLE3_3 to have inner joins within them (I only need all the matching data between them, the rest gone). Then for TABLE1, TABLE2 to have inner joins too. But from TABLE1 + TABLE2 result, some won't have a corresponding entries to TABLE3, and that's okay, I will still want it.

Using the above pseudo code if I run it as it is, obviously it will not achieve the same result.

like image 651
lorraine Avatar asked Mar 23 '17 07:03

lorraine


1 Answers

Use paretheses to force joins order, kind of

SELECT * 
FROM (
   TABLE1 
   JOIN TABLE2 ON ...)
LEFT JOIN (
    TABLE3 
    JOIN TABLE3_1 ON ...
    JOIN TABLE3_2 ON ...
    JOIN TABLE3_3 ON ...) ON ...
like image 194
Serg Avatar answered Oct 03 '22 07:10

Serg