大数据之hive:left join on左连接的使用

一、概述

left (outer) join :左连接或左外连接,把left join左边的表的记录全部找出来。系统会先用表A和表B做个笛卡儿积,然后以表A为基表,去掉笛卡儿积中表A部分为NULL的记录,最后输出结果。
双表连接条件写在on后,进行左连接时,涉及到主表、辅表,这时主表条件写在where之后,辅表条件写在and后面。

二、实例

1、表test_01,test_02结构和数据

test_01表:id和type两个字段

idtype
11
21
32

test_02表:id和type两个字段

idtype
11
22

2、SQL语句调用

--sql1
select a.*, b.* from test_01 as a left join test_02 as b on a.id = b.id and a.type = 1;
--输出结果为:
a.id	a.type	b.id	b.type
2	1	2	2
3	2	NULL	NULL
1	1	1	1
--sql2
select a.*, b.* from test_01 as a left join test_02 as b on a.id = b.id where a.type = 1;
--输出结果为:
a.id	a.type	b.id	b.type
2	1	2	2
1	1	1	1
--sql3
select a.*, b.* from test_01 as a left join test_02 as b on a.id = b.id and b.type = 1;
--输出结果为
a.id	a.type	b.id	b.type
2	1	NULL	NULL
3	2	NULL	NULL
1	1	1	1
--sql4
select a.* from test_01 as a left join test_02 as b on a.id = b.id where b.id is null;
--输出结果为:
a.id	a.type
3	2
--sql5
select a.* from test_01 as a left join test_02 as b on a.id = b.id and b.id is null;
--输出结果为
a.id	a.type
2	1
3	2
1	1

4、总结:

sql1可见,left join 中左表的全部记录将全部被查询显示,and 后面的条件对它不起作用;
除非再后面再加上where来进行筛选,这就是sql2了;
由sql3可见,and后面的条件中,右表的限制条件将会起作用;
如果筛选出a表中有b表中没有的,这就是sql4了,sql5是不正确的;

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值