全量和增量

需求:把stu表中的数据,迁移到一张新的表stu2中;
此时,stu2表可能存在,也可能不存在。
select * from stu2;

insert into stu(stuid,stuname) values(1002,'lisi');
insert into stu values(1003,'wangwu');

当stu2表不存在时:
创建stu2表,其字段与后面的select 里面的字段名一致;创建好了表之后,同时把select查询到的数据存入stu2;
如果不想导入所有数据,可以在select语句后面用where过滤;
create table stu2 as select stuid,stuname from stu;

如果表stu2存在:
直接往表中添加数据,insert后面直接跟上查询语句
insert into stu2 select stuid,stuname from stu ;

delete from stu2 where stuid>1001;
这里有两条1001-zhangsan数据,需要去除重复:
delete from stu2 where rowid not in (select min(rowid) from stu2 group by stuid,stuname)

现在stu2表里面,有一行1001-zhangsan的数据,现在需要从stu表中导入数据(需要去除重复数据)
insert into stu2 select stuid,stuname from stu where stuid>(select max(stuid) from stu2);

如果stu2表中存在1001,但是1001对应的stuname叫zs,而stu表中1001对应的stuname是zhangsan,怎么办?
merge into....


想要把stu表里面的数据,迁移到stu2表里面,有两种方式;
1.全量同步
    stu2表里先清空,再把stu表中的所有数据全部导入stu2;
    insert into stu2 select stuid,stuname from stu ;
2.增量同步
    stu2表里面已经有了一部分数据,对于stu表里面的数据,如果stu2已经存在了,就做修改;如果stu2中没有,则做增加
    
这里重点看增量同步:
比如:stu表中,有数据1001-zhangsan;stu2表里面有1001-zs:

update stu2 set stuname='zs' where stuid=1001;
commit;

stu2表示要同步到哪张表;
using stu :表示数据从哪来
on (s1.stuid=s2.stuid) :判断增量的条件
when matched : 表示如果前面的条件匹配上(stu2表里面已经存在的数据)
when not matched then :表示条件没有匹配上的时候(stu2表里没有的数据)

merge into stu2 s2 using stu s1 on (s1.stuid=s2.stuid) 
when matched then update set s2.stuname=s1.stuname where s2.stuid=s1.stuid
when not matched then insert (stuid,stuname) values(s1.stuid,s1.stuname);

执行之后,查询stu2:
select * from stu2;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

好好羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值