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子句便不会出现这样的问题.