replace into爲何很差?先刪除,後插曲,刪除時會全表掃描嗎?html
參考來自MySQL官方網絡的文檔:mysql
http://dev.mysql.com/doc/refman/5.0/en/replace.htmlsql
MySQL uses the following algorithm for REPLACE
(and LOAD DATA ... REPLACE
):網絡
Try to insert the new row into the tablecode
While the insertion fails because a duplicate-key error occurs for a primary key or unique index:htm
Delete from the table the conflicting row that has the duplicate key valueblog
Try again to insert the new row into the table事務
能夠發現,replace into會嘗試兩個步驟的動做:rem
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子句便不會出現這樣的問題.