Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple LEFT JOINs - what is the "left" table?

I've been using this for years, so it is high time to understand it fully. Suppose a query like this:

SELECT 
  *
FROM a
LEFT JOIN b ON foo...
LEFT JOIN c ON bar...

The documentation tells us that

T1 { [INNER] | { LEFT | RIGHT | FULL } [OUTER] } JOIN T2 ON boolean_expression

LEFT OUTER JOIN

First, an inner join is performed. Then, for each row in T1 that does not satisfy the join condition with any row in T2, a joined row is added with null values in columns of T2. Thus, the joined table always has at least one row for each row in T1.

The question is simple: what is T1 in this case? Is it a? Or is it a LEFT JOIN b ON foo? (or, is it the same?)

like image 335
vektor Avatar asked Mar 21 '16 15:03

vektor


People also ask

What is the left table in a left join?

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.

How join multiple tables with LEFT join?

Syntax For Left Join:SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.

Which rows do the LEFT join return?

LEFT JOIN , also called LEFT OUTER JOIN , returns all records from the left (first) table and the matched records from the right (second) table.

What is the left join?

The LEFT JOIN command returns all rows from the left table, and the matching rows from the right table. The result is NULL from the right side, if there is no match.


1 Answers

A FROM clause parses the conditions from left to right (unless overridden by parentheses). So:

FROM a 
LEFT JOIN b
     ON foo... 
LEFT JOIN c
     ON bar...

is parsed as:

FROM (
        a 
        LEFT JOIN b
           ON foo...
     ) 
LEFT JOIN c
     ON bar...

This is explained in the documentation under the join-type section of the FROM clause:

Use parentheses if necessary to determine the order of nesting. In the absence of parentheses, JOINs nest left-to-right. In any case JOIN binds more tightly than the commas separating FROM-list items.

As a consequence, a series of LEFT JOINs keeps all records in the first mentioned table. This is a convenience.

Note that the parsing of the FROM clause is the same regardless of the join type.

like image 174
Gordon Linoff Avatar answered Sep 25 '22 05:09

Gordon Linoff