right join versus left join

后端 未结 3 1081
栀梦
栀梦 2021-01-22 22:44

In this case, a left join is the same as a right join?

mysql> 
mysql> 
mysql> use usenet;show tables;describe ARTICLE;describe NEWSGROUP;
Database chang         


        
相关标签:
3条回答
  • 2021-01-22 22:54

    Not really, because RIGHT JOIN and LEFT JOIN are symmetric. That is:

    A LEFT JOIN B = B RIGHT JOIN A
    

    RIGHT JOIN is merely syntactic sugar. The optimizer can rewrite a right join to a left join:

    mysql> explain extended select * from t right join t t2 using (c1)\G
    *************************** 1. row ***************************
               id: 1
      select_type: SIMPLE
            table: t2
             type: index
    possible_keys: NULL
              key: c2
          key_len: 5
              ref: NULL
             rows: 4201
         filtered: 100.00
            Extra: Using index
    *************************** 2. row ***************************
               id: 1
      select_type: SIMPLE
            table: t
             type: eq_ref
    possible_keys: PRIMARY
              key: PRIMARY
          key_len: 4
              ref: test.t2.c1
             rows: 1
         filtered: 100.00
            Extra: 
    2 rows in set, 1 warning (0.00 sec)
    

    Note the LEFT JOIN in the optimizer re-write (the tables are swapped):

    mysql> show warnings\G
    *************************** 1. row ***************************
      Level: Note
       Code: 1003
    Message: select `test`.`t2`.`c1` AS `c1`,`test`.`t2`.`c2` AS `c2`,`test`.`t`.`c2` AS
    `c2` from `test`.`t` `t2` left join `test`.`t` on((`test`.`t`.`c1` = `test`.`t2`.`c1`))  where 1
    1 row in set (0.00 sec) 
    

    Notice that (A RIGHT JOIN B != A LEFT JOIN B) unless (A INNER JOIN B = A LEFT JOIN B). This is because A RIGHT JOIN B is not symmetrical with A LEFT JOIN B (it is symmetrical with B LEFT JOIN A).

    In your case, A RIGHT JOIN B will be the same as A LEFT JOIN B unless there are NULL values in the columns you are joining. If there are NULL values, then A LEFT JOIN B will NOT be the same as A RIGHT JOIN B. If you add new articles without adding the associated newsgroup (or vice-versa) then the results would change too.

    0 讨论(0)
  • 2021-01-22 22:58

    Codeproject has this image which explains the simple basics of SQL joins, taken from: http://www.codeproject.com/KB/database/Visual_SQL_Joins.aspx SQL joins explained enter image description here

    0 讨论(0)
  • 2021-01-22 23:13

    With your current data, yes they are the same. However as NEWSGROUP_ID is nullable then they could be different as the data changes.

    Personally I always use LEFT JOINs if possible (from primary table to child table), in fact I have only needed to use a RIGHT JOIN a couple of times in over 6 years of SQL development!

    0 讨论(0)
提交回复
热议问题