SQL 语句之insert语句插入数据:若表中有重复的主键或数据继续插入解决方案
已知條件: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);
- 1
在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的記錄
?
④最后生成的數據就會插入表中
總結
以上是生活随笔為你收集整理的SQL 语句之insert语句插入数据:若表中有重复的主键或数据继续插入解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot+mybatis多数
- 下一篇: 3月20日, Java 10 正式发布了