需求
要求将只存在于u1而不存在于u2的的ID记录全部插入u2中,并用u1中的记录更新u2中相同ID的记录。
不要被题目误导了,这个应该先更新数据,然后再插入,不要被题目的顺序误导
数据源
drop table u1;create table if not exists u1(id int,name string)row format delimitedfields 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,a2,b3,c4,d7,y8,uu2文件中的数据如下:2,bb3,cc7,yy9,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 u1left join u2 on u1.id = u2.idunionselect id, namefrom u2)insertoverwritetableu2select *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会去重如果觉得《Hive利用增量表更新全量表》对你有帮助,请点赞、收藏,并留下你的观点哦!