SQL 语句之insert语句插入数据;若表中有重复的主键或数据插入的时候要求不能报错
已知条件:MySQL数据库存在一张表,表名为teacher,主键为id,表中有4行数据select * from teacher;要求:要求使用数据库插入语句往表中插入数据,若需要插入表中的数据(或者数据的主键)如果已经在表中存在,那么要求SQL在执行的时候不能报错。例如:插入一行id=3,name=丁老师,salary=5000的记录,insert into teacher(id,name,s
·
已知条件:MySQL数据库
存在一张表,表名为teacher,主键为id,表中有4行数据
select * from teacher;
要求:要求使用数据库插入语句往表中插入数据,若需要插入表中的数据(或者数据的主键)如果已经在表中存在,那么要求SQL在执行的时候不能报错。
例如:插入一行id=3,name=丁老师,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);
在MySQL中 replace 的执行效果和 insert 的效果是一样的,不同的是replace 语句会把后来插入表中的记录替换掉已经存在于表中的记录,此法不推荐使用。
因为若此时再插入一条语句
replace into teacher(id,name,salary) values(3,’苏老师’,9000);
那么这条语句的内容会把先前插入表中的内容id=3,name=丁老师,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=3,name=丁老师,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的记录
④最后生成的数据就会插入表中
更多推荐
所有评论(0)