Which table exactly is the “left” table and “right” table in a JOIN statement (SQL)?

前端 未结 5 2092
悲哀的现实
悲哀的现实 2020-12-24 10:17

What makes a given table the left table?

Is it that the table is indicated in the \"From\" part of the query?

Or, is it the left table because it is on the l

5条回答
  •  囚心锁ツ
    2020-12-24 11:06

    Roughly "left" is the result of everything that appears first in the whole FROM clause when reading from left to right - including the result of other JOINs, sub-queries, VIEWs and STORED PROCEDURES.

    Both SQL statements are equivalent because the = operator at the ON part of the JOIN clause is symmetric (if a = b then b = a) so the result is the same no matter the order.

    The regular join shows only the lines where the ON clause of the JOIN is true, while the LEFT JOIN shows also the records from "left" if the condition is false (showing NULL for any column from "right" present in the SELECT).

    For example:

    -- People:           -- Car
    id | name            owner_id | model
    ---+------------     ---------+------------
    1  | Paul            1        | Ferrari
    2  | Nancy           2        | Porsche
    3  | Arthur          NULL     | Lamborghini
    4  | Alfred          10       | Maserati
    
    > select people.name, car.model from people join car on car.owner_id=people.id;
    
    name     | model
    ---------+--------------
    Paul     | Ferrari
    Nancy    | Porsche
    2 record(s) found
    
    > select people.name, car.model from people left join car on 
      car.owner_id=people.id;
    
    name     | model
    ---------+--------------
    Paul     | Ferrari
    Nancy    | Porsche
    Arthur   | NULL
    Alfred   | NULL     
    4 record(s) found
    
    > select people.name, car.model from people left join car on 
      people.id = car.owner_id;
    
    name     | model
    ---------+--------------
    Paul     | Ferrari
    Nancy    | Porsche
    Arthur   | NULL
    Alfred   | NULL     
    4 record(s) found
    

提交回复
热议问题