標籤:
replace into為什麼不好?先刪除,後插曲,刪除時會全表掃描嗎?
參考來自MySQL官方網路的文檔:
http://dev.mysql.com/doc/refman/5.0/en/replace.html
MySQL uses the following algorithm for REPLACE (and LOAD DATA ... REPLACE):
Try to insert the new row into the table
While the insertion fails because a duplicate-key error occurs for a primary key or unique index:
Delete from the table the conflicting row that has the duplicate key value
Try again to insert the new row into the table
可以發現,replace into會嘗試兩個步驟的動作:
1. 嘗試插入資料到表中.這個時候,如果沒有出現重複鍵的異常的話,就提交事務,結束這次的replace into操作.
2. 如果發生重複插入的異常,則先刪除帶有重複值的資料行,而後再嘗試插入資料
從上面的步驟來看,當主鍵是auto_increment欄位時,這樣的檢測是無法達到目的的.
然而有這樣的情況:
當表中的主鍵為自增長欄位,同時還存在一個唯一約束時,使用replace會造成這樣的結果:
create table t1(c1 int not null auto_increment primary key,c2 int not null unique,c3 varchar(20));
replace into t1(c2,c3) values(1,‘2‘);
replace into t1(c2,c3) values(1,‘2‘);
?
會發現,自增長欄位的主索引值是不一樣的.
此時,使用insert into on duplicate update子句便不會出現這樣的問題.
MySQL擴充功能 - 重複插入