Is left join commutative? What are its properties?

风流意气都作罢 提交于 2019-12-24 22:55:42

问题


Assume tables TableA TableB TableC and TableD:

Is the following query:

TableA INNER JOIN TableB LEFT JOIN TableC LEFT JOIN TableD

(all joined to an id column) equivalent to:

TableA INNER JOIN TableB
     INNER JOIN TableC
     LEFT JOIN TableD    

UNION  

TableA INNER JOIN TableB
    LEFT JOIN TableC ON TableB.c_id IS NULL
    LEFT JOIN TableD    

?

Note:
Or instead of union just do

TableA INNER JOIN TableB
       INNER JOIN TableC
        LEFT JOIN TableD  

And then

TableA INNER JOIN TableB
       LEFT JOIN TableC ON TableB.c_id IS NULL
       LEFT JOIN TableD    

and then combine the results

Update
Is

(A INNER JOIN B) LEFT JOIN C LEFT JOIN D 

the same as:

A INNER JOIN (B LEFT JOIN C) LEFT JOIN D

?


回答1:


Wikipedia:

"In mathematics, a binary operation is commutative if changing the order of the operands does not change the result. It is a fundamental property of many binary operations, and many mathematical proofs depend on it."

Answer:

no, a left join is not commutative. And inner join is.

But that's not really what you are asking.

Is the following query:

TableA INNER JOIN TableB LEFT JOIN TableC LEFT JOIN TableD

(all joined to an id column) equivalent to:

TableA INNER JOIN TableB
       INNER JOIN TableC
        LEFT JOIN TableD   
UNION     
TableA INNER JOIN TableB
        LEFT JOIN TableC ON TableB.c_id IS NULL
        LEFT JOIN TableD    

Answer:

Also no. Unions and joins don't really accomplish the same thing, generally speaking. In some case you may be able to write them equivalently, but I don't think so general pseudo sql you are showing. The ON constitution seemslike it should not work (maybe something about which I do not know in MySQL?)

Here is a simplified set of queries that I do think would be equivalent.

SELECT * 
  FROM TableA a 
       LEFT JOIN 
       TableB b ON a.id = b.id_a 

SELECT * 
  FROM TableA a 
       INNER JOIN 
       TableB b ON a.id = b.id_a 
UNION      
SELECT * 
  FROM TableA a  
       LEFT JOIN 
       TableB b ON a.id = b.id_a 
 WHERE TableB.id IS NULL

Edit 2:

Here's another example that is closer to your but in essence the same.

SELECT * 
  FROM            TableA a 
       INNER JOIN TableB b ON a.id = b.id_a 
        LEFT JOIN TableC c ON b.id = c.id_b 

is the same as

SELECT * 
  FROM TableA a 
       INNER JOIN TableB b ON a.id = b.id_a 
       INNER JOIN TableC c ON b.id = c.id_b 
UNION      
SELECT * 
  FROM TableA a  
       INNER JOIN TableB b ON a.id = b.id_a 
        LEFT JOIN TableC c ON b.id = c.id_b 
 WHERE TableC.id IS NULL

But I still don't think I'm answering your real question.



来源:https://stackoverflow.com/questions/23068503/is-left-join-commutative-what-are-its-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!