mysql批量更新,批量插入之replace语句/insert into... on duplicate key update语句
mysql批量更新/插入數(shù)據(jù)有以下方法,使用這些方法批量插入數(shù)據(jù)/更新數(shù)據(jù)的時候就不用在代碼層次增加判斷數(shù)據(jù)是否已存在的邏輯了。
? ?1:replace語句
? ?2:?insert into... on duplicate key update語句
所用mysql版本:
使用語法:?
replace into 表名l (id,字段1) values (1,'2'),(2,'3'),...(x,'y');insert into 表名l (id,字段1) values (1,'2'),(2,'3'),...(x,'y') on duplicate key update 字段1=values(字段1);二者結(jié)論:
1:唯一性索引沖突時,兩種方式都會增加數(shù)據(jù)表AUTO_INCREMENT的值。
2:replace遇到主鍵/唯一索引沖突是先刪除再插入,無沖突直接進行insert。
結(jié)論驗證:
?結(jié)論1:
? ? 表初始數(shù)據(jù)如下:其中id為主鍵,并且自增,uni為唯一索引。
a:?insert into... on duplicate key update驗證:
? ?執(zhí)行sql:insert into test(phone,email,uni) values ('myphon-5', 'myemail@5', 5) on duplicate key update phone='myphon-5',email = 'myemail@5',uni = 5;
? ?再執(zhí)行插入一條不指定主鍵的常規(guī)插入的sql:INSERT into test (phone,email, uni) values ('myphon-temp', 'myemail@qq.com-temp', 6);
? ?從下表數(shù)據(jù)可以看出新數(shù)據(jù)id直接從5跳過6,生成7:
? ??
?b:replace方式驗證:
? ? ?執(zhí)行sql:REPLACE into test (phone,email,uni) values ('ph-tempins', 'myemail-tempins', 7);
? ? ?再執(zhí)行插入一條新不指定主鍵的常規(guī)插入的sql:INSERT into test (phone,email, uni) values ('myphon-temp', 'myemail@qq.com-temp', 8);
? ? ?從下表數(shù)據(jù)可以看出新數(shù)據(jù)id直接從9跳過10,生成11:
??
?結(jié)論2:
? ? 官方原文:https://dev.mysql.com/doc/refman/8.0/en/replace.html
二者詳細測試:
? ?I: relace語句不帶主鍵索引與唯一索引:
? ? ? 1:表結(jié)構(gòu)
? ? 表初始數(shù)據(jù):
? 執(zhí)行sql:??REPLACE INTO test_11(username, pwd) VALUES('1', '1-pwd-new');? 后
?II: relace語句帶有主鍵索引:
? ? ?1:表結(jié)構(gòu):
? ? 2:插入初始數(shù)據(jù):
? ? 3:執(zhí)行sql:?REPLACE INTO test(ID, phone, email) VALUES(1, 'my phone', 'myemail@qq.com'); 后
III: insert into... on duplicate key update語句帶有主鍵索引:
? ?同樣對replace語句測試中的test表執(zhí)行sql:
insert into test (id,phone,email) values (1, 'myphon-new', 'myemail@qq.com-new') on duplicate key update phone='myphon-new', email = 'myemail@qq.com-new';? 結(jié)果:
? ? ? ?這里顯示受影響行為2行,結(jié)合結(jié)論1中提到的唯一性索引沖突時,兩種方式都會增加數(shù)據(jù)表AUTO_INCREMENT的值以及官方文檔的說明,筆者猜想此種方式執(zhí)行流程應該是先執(zhí)行插入操作,諾因為索引唯一性沖突導致插入失敗則進行更新操作。關(guān)于索引唯一性沖入導致的插入失敗會導致數(shù)據(jù)表AUTO_INCREMENT的值增加,這點可自行驗證。
? ? ? 官方文檔的描述如下:
? ? ?官方文檔地址:https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
IIII: insert into... on duplicate key update語句無主鍵索引,唯一索引:
? ?insert into test_11(username,pwd) values ('1-new', '1-pwd-new') on duplicate key update username='1-new', pwd = '1-pwd-new';
最后需要說的是,理論上insert into... on duplicate key update語句能比replace語句有更好的執(zhí)行效率,此外replace語句 與 insert into... on duplicate key update語句多事務并發(fā)會有死鎖的風險,參考:http://mysql.taobao.org/monthly/2015/03/01/
總結(jié)
以上是生活随笔為你收集整理的mysql批量更新,批量插入之replace语句/insert into... on duplicate key update语句的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql Communications
- 下一篇: mysql InnoDB 聚集索引,二级