SQL 语句之insert语句插入数据:若表中有重复的主键或数据继续插入解决方案

MySQL主键冲突处理技巧
本文介绍两种在MySQL中处理主键冲突的方法:使用replace语句替代insert操作,以及利用select判断式结合insert语句来避免插入已存在的主键数据时出现错误。

已知条件:MySQL数据库 
存在一张表,表名为teacher,主键为id,表中有4行数据

select * from teacher;

 

要求:要求使用数据库插入语句往表中插入数据,若需要插入表中的数据(或者数据的主键)如果已经在表中存在,那么要求SQL在执行的时候不能报错。

例如:插入一行id=3name=丁老师,salary=5000的记录,

insert into teacher(id,name,salary) values(3,'丁老师',5000);

因为id=3的主键在表中已经存在,所以强行执行SQL插入的话程序会报错。

方法(1):使用 replace 代替 insert

replace into teacher(id,name,salary) values(3,'丁老师',5000);

  • 1

    MySQL replace 的执行效果和 insert 的效果是一样的,不同的是replace 语句会把后来插入表中的记录替换掉已经存在于表中的记录,此法不推荐使用。 
    因为若此时再插入一条语句 
    replace into teacher(id,name,salary) values(3,'
    苏老师',9000); 
    那么这条语句的内容会把先前插入表中的内容id=3name=丁老师,salary=5000的记录替换掉

方法(2):结合select的判断式insert 语句

灵感代码:

insert into tableA(x,y,z) select * from tableB

模板代码:

insert into teacher(id,name,salary) select ?,?,? from teacher where not exists(select * from teacher where id=?) limit 1;

 

或者

 

insert into teacher(id,name,salary) select distinct ?,?,? from teacher where not exists(select * from teacher where id=?);

 

例子:插入一行id=3name=丁老师,salary=5000的记录

insert into teacher(id,name,salary)

select 3,'丁老师',5000 from teacher

where not exists(select * from teacher where id=3) limit 1;

或者

insert into teacher(id,name,salary)

( select 4,'白老师',4000 from teacher

where not exists(select * from teacher where id=4) limit 1);

 

 

在上面的SQL语句中:执行的原理解析:

teacher表中不存在id=3的那条记录,则生成要插入表中的数据并插入表;

teacher表中存在id=3的那条记录,则不生成要插入表中的数据。

 

其实程序可以分开看:

select * from teacher where id=3 若查询有值,则表示真,即存在id=3这条记录,若查询没有值则表示假,即不存在id=3这条记录,

 

若果不存在id=3这条记录,那么又因为 not exists 本身表示假,即不存在的意思;假假为真,所以此时程序可以形象的理解为

select 3,'丁老师',5000 from teacher where not exists (false) limit 1;

等价于

select 3,'丁老师',5000 from teacher where true limit 1;

 

所以程序就会生成一行为 3,'丁老师',5000的记录

 

最后生成的数据就会插入表中

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

学亮编程手记

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

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

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

打赏作者

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

抵扣说明:

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

余额充值