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;

可以看到结果如下:

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

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

原文地址:https://www.cnblogs.com/zifeiy/p/9983144.html