MySQL擴充功能 - 重複插入

來源:互聯網
上載者:User

標籤:

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):

  1. Try to insert the new row into the table

  2. While the insertion fails because a duplicate-key error occurs for a primary key or unique index:

    1. Delete from the table the conflicting row that has the duplicate key value

    2. 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擴充功能 - 重複插入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.