假设现在有两个表,stg_table和ods_table,两者字段一模一样(建表语句如下)。我们现在需要将stg表中的数据增量插入到ods中去。
create table stg_table(col1 varchar(5),col2 int,col3 int);
create table ods_table like stg_table;
insert into stg_table values ('a',1,1),('c',3,3);
insert into ods_table values ('a',1,1),('b',2,2);
方案1:先根据相关字段删除数据,再插入新的数据
— 1. 先删除
delete a
from ods_table a
join stg_table b
on a.col1 = b.col1 and a.col2 = b.col2 and a.col3 = b.col3;
— 2. 再插入
insert into ods_table
select *
from stg_table;
方案2:使用exists判断,将新增数据插入
insert into ods_table(col1,col2,col3)
select col1,col2,col3
from stg_table b
where not exists (
select 1 from ods_table where col1 = b.col1 and col2 = b.col2 and col3 = b.col3
);