left join 后用 on 还是 where

一、背景

前天写SQL时本想通过 A left B join on and 后面的条件来使查出的两条记录变成一条,奈何发现还是有两条。

后来发现 join on and 不会过滤结果记录条数,只会根据and后的条件是否显示 B表的记录,A表的记录一定会显示。
不管and 后面的是A.id=1还是B.id=1,都显示出A表中所有的记录,并关联显示B中对应A表中id为1的记录或者B表中id为1的记录。

二、实现

例子一

运行SQL
select * from student s left join class c on s.classId=c.id order by s.id

image

运行SQL
select * from student s left join class c on s.classId=c.id and s.name="张三" order by s.id

image

点击查看代码
select * from student s left join class c on s.classId=c.id and c.name="三年级三班" order by s.id

image

数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。

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

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

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

假设有两张表:
image

例子二

三条SQL

sql 一
select * from tab1 left join tab2 on (tab1.size = tab2.size)

image

sql 二

select * from tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name='AAA'

image

sql 三
(条件不为真也会返回左表中的记录)
select * from tab1 left join tab2 on (tab1.size = tab2.size and tab2.name='AAA')

image

三、遇到的报错

四、参考博客

https://mp.weixin.qq.com/s/qOiPoS60peFcr9E5QLJurw

posted @ 2023-09-19 14:42  林财钦  阅读(18)  评论(0)    收藏  举报