left join中 on 和where区别

当我们查询数据库时会经常关联多张表查询,这就使用到了左右连接,即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~~~~~

不足之处,请指正,谢谢!

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值