Hive利用增量表更新全量表

需求

要求将只存在于u1而不存在于u2的的ID记录全部插入u2中,并用u1中的记录更新u2中相同ID的记录。

不要被题目误导了,这个应该先更新数据,然后再插入,不要被题目的顺序误导

数据源

drop table u1;
create table if not exists u1
(
    id   int,
    name string
)
    row format delimited
        fields terminated by ','
;
drop table u2;
create table if not exists u2
(
    id   int,
    name string
)
    row format delimited fields terminated by ','
;

load data local inpath '/data/u1.txt' into table u1;
load data local inpath '/data/u2.txt' into table u2;

数据集

u1文件中的数据如下:
1,a
2,b
3,c
4,d
7,y
8,u

u2文件中的数据如下:
2,bb
3,cc
7,yy
9,pp

实现SQL

--要求将只存在于u1而不存在于u2的的ID记录全部插入u2中,并用u1中的记录更新u2中相同ID的记录。
with a as (select u1.id,
                  case when u2.id is not null then u2.name else u1.name end `name`
           from u1
                    left join u2 on u1.id = u2.id
           union
           select id, name
           from u2
)
insert
overwrite
table
u2
select *
from a;

确认结果

select * from u2;
+----+----+
|id  |name|
+----+----+
|NULL|NULL|
|1   |a   |
|2   |bb  |
|3   |cc  |
|4   |d   |
|7   |yy  |
|8   |u   |
|9   |pp  |
+----+----+

总结

  • 更新数据的时候往往union和join都要用上,join用于更新全量表的旧数据,union用于追加增量数据
  • 先更新再追加,重复的不要紧,union会去重
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值