网站首页 > 知识剖析 正文
前天写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
运行sql:
SELECT *
FROM student s
LEFT JOIN class c
ON s.classId = c.id
AND s.name = '张三'
ORDER BY s.id
运行sql:
SELECT *
FROM student s
LEFT JOIN class c
ON s.classId = c.id
AND c.name = '三年级三班'
ORDER BY s.id
数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
在使用left join时,on和where条件的区别如下:
- on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
- where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。
假设有两张表:
表1:tab2
表2:tab2
两条SQL:
第一条:
select * form tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name=’AAA’
第二条:
select * form tab1 left join tab2 on (tab1.size = tab2.size and tab2.name=’AAA’)
第一条SQL的过程:
1、中间表on条件:
tab1.size = tab2.size
2、再对中间表过滤 where 条件:
tab2.name=’AAA’
第二条SQL的过程:
1、中间表on条件:
tab1.size = tab2.size and tab2.name=’AAA’
PS:条件不为真也会返回左表中的记录
其实以上结果的关键原因就是left join,right join,full join的特殊性,不管on上的条件是否为真都会返回left或right表中的记录,full则具有left和right的特性的并集。
而inner jion没这个特殊性,则条件放在on中和where中,返回的结果集是相同的。
作者丨jcpp9527
来源丨网址:blog.csdn.net/wqc19920906/article/details/79785424
dbaplus社群欢迎广大技术人员投稿,投稿邮箱:editor@dbaplus.cn
猜你喜欢
- 2025-03-19 inner join/left join/right join的区别
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)