【SQL】轻松判断什么时候用inner join 什么时候用left/right join

如果需要取的表中的字段信息为必须不为空字段,则用inner join;如果可为空,或者可有可没有,则用left join;right join 用法和left join 类似,不常用;union 合并去重;union all 合并不去重

语法:

*select * from 表A    innner join 表B  on 条件*
     取的是A表和B表的交集,*所取数据均有值,为空则舍去*
select * from 表A    left join 表B  on 条件
      以A表为准,取A表的全部数据,联接B表的数据
select * from 表A    right join 表B  on 条件
      以B表为准,取B表的全部数据,联接A表的数据

举个栗子

表A

CREATE TABLE stu(
id int, 
name varchar(10));
INSERT INTO stu VALUES (1,'a'),(2,'b'),(3,'c') ;    
idname
1a
2b
3c

表B

CREATE TABLE score( 
name varchar(10),
score int);
INSERT INTO score VALUES ('b',90),('c',85),('d',100);
namescore
b90
c85
d100
  • inner join结果
SELECT * FROM stu A
inner JOIN score b ON a.name=b.name
idnamenamescore
2bb90
3cc85
  • left join 结果
SELECT * FROM stu A
LEFT JOIN score b ON a.name=b.name
idnamenamescore
1anullnull
2bb90
3cc85

left join 常用于过滤,取A表有但B表没有的,常在后面加上
WHERE b.name IS null 使用,输出结果如下

idnamenamescore
1anullnull
  • right join结果
idnamenamescore
2bb90
3cc85
nullnulld100
  • full join结果
idnamenamescore
1anullnull
2bb90
3cc85
nullnulld100
  • 22
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值