sql中过滤条件放在on和where中的区别,inner join没区别。后来才想起来,连接查询除了inner join还有right join,left join。
join过程可以这样理解:首先两个表做一个笛卡尔积,on后面的条件是对这个笛卡尔积做一个过滤形成一张临时表,如果没有where就直接返回结果,如果有where就对上一步的临时表再进行过滤。下面看实验:
先准备两张表:
先执行inner join:
select * from person p inner join account a on p.id=a.id and p.id!=4 and a.id!=4;
![](https://i-blog.csdnimg.cn/blog_migrate/1b0f4857cedbf2f6727a34c689735268.png)
select * from person p inner join account a on p.id=a.id where p.id!=4 and a.id!=4;
![](https://i-blog.csdnimg.cn/blog_migrate/1b2efc47d625efa9990a044f111fbbed.png)
结果没有区别,前者是先求笛卡尔积然后按照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;
![](https://i-blog.csdnimg.cn/blog_migrate/60b74afc944257d3215999bb6207f410.png)
这下看出来不对了,id为4的记录还在,这是由left join的特性决定的,使用left join时on后面的条件只对右表有效(可以看到右表的id=4的记录没了)
select * from person p left join account a on p.id=a.id where p.id!=4 and a.id!=4;
![](https://i-blog.csdnimg.cn/blog_migrate/eed98e705b1ed7c5f407862801b73c8e.png)
where的过滤作用就出来了。。。
右连接的原理是一样的。。
到这里就真相大白了inner join中on和where没区别,右连接和左连接就不一样了。