Left join 中where on 的 区别

  • 问题:

Left join中where, on区别

table a(id, type):
id     type
1      1        
2      1         
3      2  
table b(id, class):
id    class
1      1
2      2
sql语句1:select a.*, b.* from a left join b on a.id = b.id and a.type = 1;
sql语句2:select a.*, b.* from a left join b on a.id = b.id and b.class = 1;
sql语句3:select a.*, b.* from a left join b on a.id = b.id where a.type = 1;
sql语句1的执行结果为:
a.id    a.type    b.id    b.class
1        1            1        1
2        1            2        2
3        2              
sql语句2的执行结果为:
a.id    a.type    b.id    b.class
1        1            1        1
2        1           
3        2           
sql语句3的执行结果为:
a.id    a.type    b.id    b.class
1        1            1        1
2        1            2        2

  • 结论:

//此表结论:
left join 中左表的全部记录将全部被查询显示,on 后面的条件对左边的表不起作用,但对右表的限制条件将会起作用。
//此次结论:
数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给 用户。
1、 on 条件是在生成临时表时使用的条件,返回左边的全部记录。
2、where 条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有 left join 的含义(必须 返回左边表的记录)了,条件不为真的就全部过滤掉。


猜你喜欢

转载自vincentboy.iteye.com/blog/1654652