mysql中left join设置条件在on与where时的用法区别分析
作者:怀素真 时间:2024-01-12 15:05:52
本文实例讲述了mysql中left join设置条件在on与where时的用法区别。分享给大家供大家参考,具体如下:
一、首先我们准备两张表来进行测试。
CREATE TABLE `a` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(32) DEFAULT '' COMMENT '名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `b` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`a_id` int(11) DEFAULT '0' COMMENT 'a表ID',
`name` varchar(32) DEFAULT '' COMMENT '名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
两个表的数据如图所示:
运行下面左连接查询:
select * from a left join b on a.id = b.a_id;
我们分别在on和where后面加上条件,看看执行结果是否相同。
select * from a left join b on a.id = b.a_id and b.id > 3;
select * from a left join b on a.id = b.a_id where b.id > 3;
上面的两条语句,条件我们设置的是一样的都是b.id > 3,为什么显示结果不同。
sql语句查询的关键字顺序一般为 from > where > group by > having > order by
left join 在 from范围,on 条件会先对 left join 的右表进行筛选,筛选完后的结果 where 再进行筛选。
多个 left join 会生成一张临时表,on 条件是对 left join 右表进行条件过滤,where 条件针对最后生成的临时表进行过滤。
所以:
b.id > 3 的条件如果写在 on 后面,则是先对右边表(关联表)进行筛选,得出符合条件的行,然后主表 left join ,返回主表所有的行,右边表没匹配上的用 null 表示。
b.id > 3 的条件如果写在 where 后面,则是先主表 left join 右边表(关联表),返回所有的行,然后 where 条件再对结果进行筛选。
注意:on 后面的条件是针对右边的表(关联表),对主表没什么作用。
select * from a left join b on a.id = b.a_id and a.id > 3;
我们在on 后面添加了对主表的条件 a.id > 3,不过主表的数据仍然全部显示出来了,但是影响了右边表(关联表)的显示。
如果想要对主表进行筛选,应该把条件写在where后。
select * from a left join b on a.id = b.a_id where a.id > 3;
希望本文所述对大家MySQL数据库计有所帮助。
来源:https://www.cnblogs.com/jkko123/p/10148927.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python编程进阶之异常处理用法实例分析
mysql 5.7.21 安装配置方法图文教程(window)
手把手带你走进Go语言之常量解析
![](https://img.aspxhome.com/file/2023/8/127398_0s.gif)
MySQL replace into 语句浅析(一)
![](https://img.aspxhome.com/file/2023/4/129894_0s.jpg)
基于Python中numpy数组的合并实例讲解
![](https://img.aspxhome.com/file/2023/2/83702_0s.jpg)
vue中提示$index is not defined错误的解决方式
Golang函数这些神操作你知道哪些
mac os10.12安装mysql5.7.18教程
![](https://img.aspxhome.com/file/2023/7/76457_0s.jpg)
python生成可执行exe控制Microsip自动填写号码并拨打功能
![](https://img.aspxhome.com/file/2023/6/61736_0s.png)
教你用python提取txt文件中的特定信息并写入Excel
![](https://img.aspxhome.com/file/2023/2/107262_0s.png)
Python基于Serializer实现字段验证及序列化
python requests.get带header
![](https://img.aspxhome.com/file/2023/1/97091_0s.jpg)
Javascript实现数组中的元素上下移动
Python 动态导入对象,importlib.import_module()的使用方法
Python基于ImageAI实现图像识别详解
巧用Javascript的逻辑运算符
python re正则表达式模块(Regular Expression)
由Python编写的MySQL管理工具代码实例
Python的Flask框架中web表单的教程
![](https://img.aspxhome.com/file/2023/4/86634_0s.jpg)
python获取指定目录下所有文件名列表的方法
![](https://img.aspxhome.com/file/2023/9/104879_0s.png)