合并两个表,如果有相同记录合并记录 如果没有则插入
create table test(
id number primary key,
sex number
)
insert into test values(1,1);
insert into test values(2,2);
insert into test values(3,3);
create table test1(
id number primary key,
sex number
)
insert into test1 values(2,2);
insert into test1 values(3,3);
insert into test1 values(4,4);
将test1表合并到test表,如果test1表中的id和test表中有重复则将sex字段相加,如果test1中有记录,test中没有记录,则在test表中新增一条数据
merge into test a
using (select b.id,b.sex from test1 b) c
on (a.id=c.id)
when matched then update set a.sex=a.sex+c.sex
when not matched then insert (a.id,a.sex) values (c.id, c.sex)
最终结果:
select * from test
ID SEX
---------- ----------
1 1
2 4
3 6
4 4