Understanding the number of matched rows in LEFT JOIN

后端 未结 5 1642
野趣味
野趣味 2021-01-17 07:01

Here is my table structure: SQL Fiddle

CREATE TABLE mytable (
    id int,
    related int
);

INSERT into mytable VALUES(1, NULL);
INSERT into mytable VALUES         


        
5条回答
  •  無奈伤痛
    2021-01-17 07:32

    First query: t1.related = t2.id

    t1              joined t2
    id   related  | id   related
    --------------+-------------
    1    NULL     | --   --
    2    1        | 1    NULL
    3    1        | 1    NULL
    

    An inner join would result in only two rows, but the outer join also preserves the first row that has no match.

    Second query: t1.id = t2.related

    t1              joined t2
    id   related  | id   related
    --------------+-------------
    1    NULL     | 2    1
    1    NULL     | 3    1
    2    1        | --   --
    3    1        | --   --
    

    Here too, an inner join would result in only two rows, but the outer join also preserves the two rows that have no match.

提交回复
热议问题