MySQL中使用replace into语句批量更新表数据

作为示例,我们在这里使用名为testdb的数据库,并且在其中创建两张一模一样的表:

drop table if exists test_table_1;
create table test_table_1 (
    name varchar(30) primary key,
    age integer
);
drop table if exists test_table_2;
create table test_table_2 (
    name varchar(30) primary key,
    age integer
);

然后我们往两张表里面插入一些数据,其中test_table_1中我们插入3组数据:

insert into test_table_1 (name, age) values ("刘德华", 57), ("周杰伦", 39), ("周润发", 61);

但是我们发现除了这三个人以外,我还要新增两个人,并且周润发的年龄信息也填写错了,那么我暂时先把信息插入到test_table_2中:

insert into test_table_2 (name, age) values ("陈绮贞", 43), ("范晓萱", 41), ("周润发", 63);

然后我们尝试一下,通过以下replace into语句将test_table_2中的信息更新到test_table_1中:

replace into test_table_1 select * from test_table_2;

通过如下语句查看test_table_1的结果:

select * from test_table_1;

可以看到结果如下:

nameage
刘德华57
周杰伦39
周润发63
范晓萱41
陈绮贞43

我们往test_table_1中成功新增了两位女歌手,同时也修改了周润发的年龄。
可以看到,replace into语句会更具主键是否存在来决定是进行insert操作还是update操作,是一个非常有用的指令。

转载于:https://www.cnblogs.com/zifeiy/p/9983144.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值