SQL 语句之insert语句插入数据:若表中有重复的主键或数据继续插入解决方案
已知條件:MySQL數(shù)據(jù)庫(kù)?
存在一張表,表名為teacher,主鍵為id,表中有4行數(shù)據(jù)
select * from teacher;
?
要求:要求使用數(shù)據(jù)庫(kù)插入語(yǔ)句往表中插入數(shù)據(jù),若需要插入表中的數(shù)據(jù)(或者數(shù)據(jù)的主鍵)如果已經(jīng)在表中存在,那么要求SQL在執(zhí)行的時(shí)候不能報(bào)錯(cuò)。
例如:插入一行id=3,name=丁老師,salary=5000的記錄,
insert into teacher(id,name,salary) values(3,'丁老師',5000);
因?yàn)?/span>id=3的主鍵在表中已經(jīng)存在,所以強(qiáng)行執(zhí)行SQL插入的話(huà)程序會(huì)報(bào)錯(cuò)。
方法(1):使用 replace 代替 insert
replace into teacher(id,name,salary) values(3,'丁老師',5000);
- 1
在MySQL中 replace 的執(zhí)行效果和 insert 的效果是一樣的,不同的是replace 語(yǔ)句會(huì)把后來(lái)插入表中的記錄替換掉已經(jīng)存在于表中的記錄,此法不推薦使用。?
因?yàn)槿舸藭r(shí)再插入一條語(yǔ)句?
replace into teacher(id,name,salary) values(3,'蘇老師',9000);?
那么這條語(yǔ)句的內(nèi)容會(huì)把先前插入表中的內(nèi)容id=3,name=丁老師,salary=5000的記錄替換掉方法(2):結(jié)合select的判斷式insert 語(yǔ)句
靈感代碼:
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語(yǔ)句中:執(zhí)行的原理解析:
若teacher表中不存在id=3的那條記錄,則生成要插入表中的數(shù)據(jù)并插入表;
若teacher表中存在id=3的那條記錄,則不生成要插入表中的數(shù)據(jù)。
?
其實(shí)程序可以分開(kāi)看:
① select * from teacher where id=3 若查詢(xún)有值,則表示真,即存在id=3這條記錄,若查詢(xún)沒(méi)有值則表示假,即不存在id=3這條記錄,
?
②若果不存在id=3這條記錄,那么又因?yàn)?/span> not exists 本身表示假,即不存在的意思;假假為真,所以此時(shí)程序可以形象的理解為
select 3,'丁老師',5000 from teacher where not exists (false) limit 1;
等價(jià)于
select 3,'丁老師',5000 from teacher where true limit 1;
?
③所以程序就會(huì)生成一行為 3,'丁老師',5000的記錄
?
④最后生成的數(shù)據(jù)就會(huì)插入表中
總結(jié)
以上是生活随笔為你收集整理的SQL 语句之insert语句插入数据:若表中有重复的主键或数据继续插入解决方案的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: springboot+mybatis多数
- 下一篇: MyBatis——动态SQL讲解