MySQL拡張機能-繰り返し挿入

2215 ワード

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は2つのステップの動作を試みることがわかります.
    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');
    MySQL扩展功能 - 重复插入
    replace into t1(c2,c3) values(1,'2');
    MySQL扩展功能 - 重复插入
    自己成長フィールドの主キー値が異なることがわかる.
    この場合、insert into on duplicate update句を用いると、このような問題は発生しない.