您好,欢迎来到九壹网。
搜索
您的当前位置:首页Mysql—实现批量插入,存在就更新,不存在就插入

Mysql—实现批量插入,存在就更新,不存在就插入

来源:九壹网

Mysql插入数据的SQL语句主要有:

1、insert into表示插入数据,数据库会检查主键,如果出现重复会报错;

2、replace into表示插入替换数据,需求表中有PrimaryKey,或者unique索引,如果数据库已经存在数据,则用新数据替换,如果没有数据效果则和insert into一样;

3、insert ignore表示,如果表中如果已经存在相同的记录,则忽略当前新数据;

create table testtb(  
id int not null primary key,  
name varchar(50),  
age int 
);  
insert into testtb(id,name,age)values(1,'bb',13);  
select * from testtb;  
insert ignore into testtb(id,name,age)values(1,'aa',13);  
select * from testtb;  
replace into testtb(id,name,age)values(1,"aa",12);  
select * from testtb;


4、on duplicate key update 使用该语法可在插入记录的时候先判断记录是否存在,如果不存在则插入,否则更新,很方便,无需执行两条SQL 

注:需要设置Mysql表的unique唯一索引值

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 91gzw.com 版权所有 湘ICP备2023023988号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务