解析sql语句中left_join、inner_join中的on与where的区别
时间:2024-01-25 08:18:24
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 where a.type = 1;
sql语句3:select a.*, b.* from a left join b on a.id = b.id and b.class = 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 2 2
sql语句3的执行结果为:
a.id a.type b.id b.class
----------------------------------------
1 1 1 1
2 1
3 2
由sql语句1可见,left join 中左表的全部记录将全部被查询显示,on 后面的条件对它不起作用,除非再后面再加上where来进行筛选,这就是sql语句2了;由sql语句3可见,on后面的条件中,右表的限制条件将会起作用。
**************************************************************************
sql语句4:select a.*, b.* from a inner join b on a.id = b.id and a.type = 1;
sql语句5:select a.*, b.* from a inner join b on a.id = b.id where a.type = 1;
sql语句6:select a.*, b.* from a, b where a.id = b.id and a.type = 1;
sql语句7:select a.*, b.* from a, b where a.type = 1 and a.id = b.id;
这四条语句的执行结果一样,如下:
a.id a.type b.id b.class
----------------------------------------
1 1 1 1
2 1 2 2
由此可见,inner join 中on后面的限制条件将全部起作用,这与where的执行结果是一样的。另外,where语句与inner join确实能得到相同的结果,只是效率不同(这个我没有测试过,不过我相信这个结论)。
但是sql语句6是否比sql语句7的效率要低一些,我没有足够的数据量来测试,不过我也相信是如此的。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Golang使用lua脚本实现redis原子操作
![](https://img.aspxhome.com/file/2023/7/101057_0s.png)
利用Python+eval函数构建数学表达式计算器
Python操作lxml库实战之Xpath篇
![](https://img.aspxhome.com/file/2023/2/118622_0s.png)
Python 控制终端输出文字的实例
Mootools 1.2教程(21)——类(二)
mysql压缩包版zip安装配置方法
![](https://img.aspxhome.com/file/2023/0/72440_0s.jpg)
Python控制台输出时刷新当前行内容而不是输出新行的实现
Mac系统重置PostgreSQL密码的方法示例代码
Vue2子组件绑定 v-model,实现父子组件通信方式
![](https://img.aspxhome.com/file/2023/8/130068_0s.png)
关于tensorflow的几种参数初始化方法小结
Python实现随机生成算术题的示例代码
![](https://img.aspxhome.com/file/2023/3/114533_0s.jpg)
python读写csv文件方法详细总结
python中apply函数详情
![](https://img.aspxhome.com/file/2023/1/87941_0s.png)
jQuery判断checkbox是否选中的3种方法
![](https://img.aspxhome.com/file/2023/6/135846_0s.png)
Python中多个数组行合并及列合并的方法总结
php使用递归与迭代实现快速排序示例
ActiveMQ:使用Python访问ActiveMQ的方法
![](https://img.aspxhome.com/file/2023/8/110038_0s.jpg)
Python使用正则表达式过滤或替换HTML标签的方法详解
关于python通过新建环境安装tfx的问题
![](https://img.aspxhome.com/file/2023/1/109641_0s.jpg)