MySQL扩展功能 - 重复插入

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

 

posted @ 2015-01-26 12:32  老玉米  阅读(271)  评论(0编辑  收藏  举报