当我们查询数据库时会经常关联多张表查询,这就使用到了左右连接,即left join、rigth join....。
而往往在使用左右连接时,筛选条件on和where在使用时容易出错,这次我们就以left join为例,简单讲述下on和where的用法。
首先我们要清楚左右连接的原理:在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
on和where的用法:
1.left join 左连接:展示左表所有数据,右表符合on条件的数据,右表不符合的则为空显示。
2.where条件:在生成临时表基础上,再加条件限制。
准备两张测试表bbb和bbb1来具体说明下:
bbb表结构如下:
id age
1 18
2 19
3 20
bbb1表结构如下:
id name
1 小米
8 锤子
10 苹果
执行sql语句:
1.select * from bbb b left join bbb1 b1 on b.id = b1.id ;
左表的数据都会展示出来,并展示右表中满足on条件的
id age id1 name
1 18 1 小米
2 19 null null
3 20 null null
2.select * from bbb b left join bbb1 b1 on b.id = b1.id and b1.name='小米';
左表的数据都会展示出来,并展示右表中id、name满足条件的
id age id1 name
1 18 1 小米
2 19 null null
3 20 null null
select * from bbb b left join bbb1 b1 on b.id = b1.id and b1.name='苹果';
左表的数据都会展示出来,右表中id、name都满足条件的无,就会显示null
id age id1 name
1 18 null null
2 19 null null
3 20 null null
3.select * from bbb b left join bbb1 b1 on b.id = b1.id where b1.name='小米';
先产生一张临时表,如下:
id age id1 name
1 18 1 小米
2 19 null null
3 20 null null
再用where条件过滤,只有一条符合,如下显示。
id age id1 name
1 18 1 小米
end~~~~~
不足之处,请指正,谢谢!