简体   繁体   中英

Outer left join of inner join and regular table

For the first time in my professional career I found the need of join the result of a join with a table being the first join an inner join and the second a left outer join.

I came to this solution:

SELECT * FROM
(
    TableA INNER JOIN TableB ON
    TableA.foreign = TableB.id
)
LEFT OUTER JOIN TableC
ON TableC.id = TableB.id

I know I could create a view for the first join but I wouldn't like to create new objects in my database.

Is this code right? I got coherent results but I would like to verify if it is theoretically correct. Do you have any suggestion to improve this approach?

You should do it in a simpler way.

SELECT * FROM
TableA
INNER JOIN TableB ON TableA.foreign = TableB.id
LEFT OUTER JOIN TableC ON TableB.id = TableC.id

Usually it is done that way.

I believe you are looking for something like this:

SELECT *, t.otherFields
FROM
(
    SELECT TableB.id, otherFields FROM TableA
    INNER JOIN TableB ON
    TableA.foreign = TableB.id
) t
LEFT OUTER JOIN TableC
ON TableC.id = t.id
SELECT * 
FROM TableA 
    INNER JOIN TableB ON
        TableA.foreign = TableB.id
LEFT OUTER JOIN TableC
    ON TableC.id = TableB.id

Also fine

Yes it is correct, but it does nothing different than the same (simpler) query without the parentheses:

SELECT  * 
FROM    TableA 
        INNER JOIN TableB 
            ON TableA.foreign = TableB.id
        LEFT OUTER JOIN TableC
            ON TableC.id = TableB.id;

SQL Fiddle showing both queries with the same result

Also worth noting that both queries have exactly the same execution plan

The parentheses are used when you need to left join on the results of an inner join, eg If you wanted to return only results from table b where there was a record in tableC, but still left join to TableA you might write:

SELECT  * 
FROM    TableA 
        LEFT OUTER JOIN TableB 
            ON TableA.foreign = TableB.id
        INNER JOIN TableC
            ON TableC.id = TableB.id;

However this effectively turns the LEFT OUTER JOIN on TableB into an INNER JOIN because of the INNER JOIN below. In this case you would use parentheses to alter the JOIN as required:

SELECT  * 
FROM    TableA 
        LEFT OUTER JOIN (TableB 
        INNER JOIN TableC
            ON TableC.id = TableB.id)
            ON TableA.foreign = TableB.id;

SQL Fiddle to show difference in results when adding parentheses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM