首页 笔记 图片 查字 
所属分类:MySQL
浏览:55
内容:

原因是使用了sql语句:INSERT ... ON DUPLICATE KEY UPDATE ... 显示影响行数2。

官方文档说明:
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values
影响行数1表示插入成功,影响行数2表示更新成功,影响行数0表示记录数据不变未更新。

执行 select @@innodb_autoinc_lock_mode; 结果为:2

参数 innodb_autoinc_lock_mode 控制着 有auto_increment列的表插入数据时相关锁的行为:有0,1,2 这3个级别
分别对应:0=tradition,1=consecutive,2=interleaved

tradition 模式:会产生表级的auto_inc锁,直到sql语句执行完成才释放。
consecutive 模式:
interleaved 模式:没有表级auto_inc锁,auto_increment值可能不连续。

所以当insert失败时,对应的id会被抛弃,就会记录下一个id作为最新值,所以就会出现自增id不连续增加的情况。

解决方法:
1.先检查数据是否存在,然后再更新。
2.删除自增字段。

自增字段的初始化:
如果删除所有记录,然后重新写入记录,自增字段不会从1开始分配,而是从自增字段最大值+1的值开始。
如果删除所有记录,并且让自增字段从1开始,执行SQL语句:alter table 表名 auto_increment=1;