當批量插入數(shù)據(jù)時,發(fā)現(xiàn)插入的這批數(shù)據(jù)中,有某些記錄存在唯一鍵沖突,這種情況特別是在多線程進行數(shù)據(jù)插入時,會造成異常導致處理終止或者catch異常忽略部分數(shù)據(jù)。有什么好的辦法對這些沖突的記錄進行處理呢?
MySQL插入記錄時,結(jié)果提示主鍵沖突,怎么辦?
當批量插入數(shù)據(jù)時,發(fā)現(xiàn)插入的這批數(shù)據(jù)中,有某些記錄存在唯一鍵沖突,這種情況特別是在多線程進行數(shù)據(jù)插入時,會造成異常導致處理終止或者catch異常忽略部分數(shù)據(jù)。有什么好的辦法對這些沖突的記錄進行處理呢?
下面提供三種處理方式
1. Ignore關(guān)鍵詞
某些場景下,我們需要批量插入的數(shù)據(jù),某些已經(jīng)在DB中了,我們希望在出現(xiàn)沖突時,直接跳過,把能插入的都插入就好,這種情況下,使用ignore關(guān)鍵詞就比較合適了。
一個實際的case如下:
INSERT IGNORE INTO test.licenses
(license_id,organization_id,license_type,product_name,license_max,license_allocated,comment) VALUES
('08dbe05-606e-4dad-9d33-90ef10e334f9','442adb6e-fa58-47f3-9ca2-ed1fecdfe86c','core-prod','WildCat Application Gateway',16,16,NULL),
('38777179-7094-4200-9d61-edb101c6ea88','442adb6e-fa58-47f3-9ca2-ed1fecdfe86c','user','Spring',100,6,NULL);
執(zhí)行截圖如下, 注意統(tǒng)計框中的內(nèi)容,表示忽略了一條,執(zhí)行插入成功一條

2. Replace Into方式
如果在批量插入中,我們希望用新的數(shù)據(jù)替換掉沖突的數(shù)據(jù),這個時候就可以使用replace into了。
語法如下:
REPLACE INTO test.licenses
(license_id,organization_id,license_type,product_name,license_max,license_allocated,comment) VALUES
('38777179-7094-4200-9d61-edb101c6ea88','442adb6e-fa58-47f3-9ca2-ed1fecdfe86c','core-prod','Spring Core',100,8,NULL);
執(zhí)行截圖如下,注意紅框中,當某條記錄沖突之后并替換,其影響行數(shù)為2, 其實際過程是
- 刪除沖突數(shù)據(jù)
- 插入新的數(shù)據(jù)

3. ON DUPLICATE KEY UPDATE
還有一種情況,我們希望在出現(xiàn)沖突時,只更新某些數(shù)據(jù),這個時候可以在insert語句的最后加上on duplicate key update了
語法如下
INSERT INTO test.licenses
(license_id,organization_id,license_type,product_name,license_max,license_allocated,comment) VALUES
('38777179-7094-4200-9d61-edb101c6ea88','442adb6e-fa58-47f3-9ca2-ed1fecdfe86c','user','Spring',100,6,NULL)
on duplicate key update license_allocated = 12;
執(zhí)行截圖如下,這個是在原記錄的基礎(chǔ)上執(zhí)行更新指定key的value, 比如上面的插入中,當沖突時,我們只更新license_allocated字段,而其它的字段沒有更新

