What's the difference between where clause and on clause when table left join?

后端 未结 6 1571
深忆病人
深忆病人 2020-11-27 18:28

SQL1:

select t1.f1,t2.f2 
from t1 
   left join t2 on t1.f1 = t2.f2 and t1.f2=1 and t1.f3=0 

SQL2:

select t1.f1,t2.f2 
from         


        
6条回答
  •  被撕碎了的回忆
    2020-11-27 19:21

    The two queries are NOT identical.

    Mark Bannister was right in pointing out that the where clause is applied to the whole result set but the on clause applies to the join.

    In your case, for SQL 1 LEFT JOIN conditions filter joins on the right but the left side is always returned before any WHERE filtering. Since there are no WHERE conditions all of t1 is always returned.

    In SQL 2, the LEFT JOIN conditions filter some results showing up on the right but again all t1 is returned. But this time the WHERE conditions may filter some records of t1 away.

    INSERT INTO `t1` (`f1`,`f2`,`f3`) VALUES (1,1,1); INSERT INTO `t2` (`f3`) VALUES (1);

    Since they point to different logic the query must be written based on that and it gives us great power and flexibility.

    An INNER JOIN however returns the same result so yes check the optimiser.

提交回复
热议问题