关系型数据库支持的DML(delete/update/merge)SQL ,在maxcompute(ODPS)该如何写

174 阅读2分钟
原文链接: click.aliyun.com

关系型数据库支持的DML(delete/update/merge)SQL ,在maxcompute(ODPS)该如何写

暮角 2018-12-03 10:51:44 浏览131 评论0
  • SQL
  • 数据库
  • odps
  • string
  • DML
  • update
  • delete
  • MaxCompute
  • merge

摘要: 关系型数据库支持的DML(delete/update/merge)SQL ,在maxcompute(ODPS)该如何写? 总有人问,现写了一个例子,应该可以说明了。 有问题,欢迎大家指正。

--关系型数据库支持的 delete/update/merge SQL ,在ODPS该如何写

-- 上日全量表
table1(key1 string,key2 string,col1 string,col2 string);
-- 今日增量表
table2(key1 string,key2 string,col1 string,col2 string);
-- 今日增量表(删除)
table3(key1 string,key2 string,col1 string,col2 string);

--1.update(table2 表中的记录的值,更新到table1表中)
insert overwrite table table1
select t1.key1
      ,t1.key2
      ,case when t2.key1 is not null then t2.col1 else t1.col1 end as col1
      ,case when t2.key1 is not null then t2.col2 else t1.col2 end as col2
  from table1 t1
  left outer join table2 t2 on t1.key1=t2.key1 and t1.key2 = t2.key2
;

--2.delete(table2 表中的记录,从table1表中删除)
insert overwrite table table1
select t1.key1
      ,t1.key2
      ,t1.col1
      ,t1.col2
  from table1 t1
  left outer join table2 t2 on t1.key1=t2.key1 and t1.key2 = t2.key2
 where t2.key1 is null
;
--3.merge(没有del)
insert overwrite table table1
select 
  from(
-- 先把上日存在,今日也存在的记录从上日表中排除。剩下的就是今日没有更新的记录
select t1.key1
      ,t1.key2
      ,t1.col1
      ,t1.col2
  from table1 t1
  left outer join table2 t2 on t1.key1=t2.key1 and t1.key2 = t2.key2
 where t2.key1 is null
 union all
-- 再合并上今日增量,就是今天的全量
select t2.key1
      ,t2.key2
      ,t2.col1
      ,t2.col2
  from table2 t2)tt
;

--2.merge(有del)
insert overwrite table table1
select 
  from(
-- 先把上日存在,今日也存在的记录从上日表中排除,再把今日删除的记录排除。剩下的就是今日没有更新的记录
select t1.key1
      ,t1.key2
      ,t1.col1
      ,t1.col2
  from table1 t1
  left outer join table2 t2 on t1.key1=t2.key1 and t1.key2 = t2.key2
  left outer join table3 t3 on t1.key1=t3.key1 and t1.key2 = t3.key2
 where t2.key1 is null or t2.key1 is null
 union all
-- 再合并上今日增量,就是今天的全量
select t2.key1
      ,t2.key2
      ,t2.col1
      ,t2.col2
  from table2 t2)tt
;

-- 暮角 15901445705 update at 20181203 
【云栖快讯】阿里云栖开发者沙龙(Java技术专场)火热来袭!快来报名参与吧!  详情请点击
分享到:

相关文章

网友评论