在join中,on和where的区别

两个表在,join时,首先做一个笛卡尔积,on后面的条件是对这个笛卡尔积做一个过滤形成一张临时表,如果没有where就直接返回结果,如果有where就对上一步的临时表再进行过滤。

在使用left  jion时,on和where条件的区别如下:

1、on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。

2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left  join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉

先准备两张表:

 

inner join:

select * from person p inner join account a on p.id=a.id and p.id!=4 and a.id!=4;

select * from person p inner join account a on p.id=a.id where p.id!=4 and a.id!=4;

结果没有区别,前者是先求笛卡尔积然后按照on后面的条件进行过滤,后者是先用on后面的条件过滤,再用where的条件过滤。

 

left join:

select * from person p left join account a on p.id=a.id and p.id!=4 and a.id!=4;

select * from person p left join account a on p.id=a.id where p.id!=4 and a.id!=4;

在on为选择条件时,id为4的记录还在,这是由left join的特性决定的,使用left join时on后面的条件只对右表有效(可以看到右表的id=4的记录为NULL)

在where为选择条件时,where过滤掉了左表中的内容。

 

原文:

https://blog.csdn.net/u013468917/article/details/61933994

https://www.cnblogs.com/guanshan/articles/guan062.html

https://blog.csdn.net/qq_34778597/article/details/82967016

posted @ 2019-02-20 11:29  小时候挺菜  阅读(9035)  评论(2编辑  收藏  举报