首页 > 数据库技术 > 详细

MySQL扩展功能 - 重复插入

时间:2015-01-26 13:23:19      阅读:292      评论:0      收藏:0      [点我收藏+]

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扩展功能 - 重复插入

原文:http://www.cnblogs.com/laoyumi/p/4249984.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!