on 条件是在生成临时表时使用的条件,它不管 on 中的条件是否为真,都会返回左边表中的记录。where 条件是在临时表生成好后,再对临时表进行过滤的条件。 |
数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
在使用 left jion 时,on 和 where 条件的区别如下:
假设有两张表:
表1:tab2
id | size |
1 | 10 |
2 | 20 |
3 | 30 |
表2:tab2
size | name |
10 | AAA |
20 | BBB |
20 | CCC |
两条 SQL:
select * from tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name=‘AAA‘ select * from tab1 left join tab2 on (tab1.size = tab2.size and tab2.name=‘AAA‘)
第一条SQL的过程:
|
第二条SQL的过程:
|
其实以上结果的关键原因就是 left join、right join、full join 的特殊性,不管 on 上的条件是否为真都会返回 left 或 right 表中的记录,full 则具有 left 和 right 的特性的并集。 而 inner jion 没这个特殊性,则条件放在 on 中和 where 中,返回的结果集是相同的。
本文地址:https://www.linuxprobe.com/what-is-the-4.html
原文:https://www.cnblogs.com/cainiaoyige1/p/14858597.html