首页 > 数据库技术 > 详细

mysql insert操作失败后id 在auto_increment下仍会自增的解决办法

时间:2020-01-27 15:37:56      阅读:218      评论:0      收藏:0      [点我收藏+]

在使用golang go-sql-driver操作mysql时,往tag表插入一条新数据时,如果插入失败,id仍会自增,插入数据失败次数过多时,id就看起来十分混乱。
所以我就在搜索下原因,发现是InnoDB的机制,大致就是说InnoDB的innodb_autoinc_lock_mode模式下,自增计数器在操作失败的情况下仍会增加。一般情况下如果担心id增加超过范围,可以把id的类型改为BIGINT。

create table tag
(
    id     int auto_increment primary key,
    gender int         null,
    name   varchar(50) null,
    constraint tag_name_gender_uindex
        unique (name, gender)
)ENGINE=InnoDB;

插入一条记录

常规写法:

insert ignore into tag (name,gender) values ('anime',2);

ignore 是为了插入失败时不报错。
修改的写法:

insert ignore into tag (name,gender) 
select * from (SELECT 'anime',2) AS tmp 
where not exists (
    select * from tag where name='anime' AND gender=2
);

参考文章:

mysql insert操作失败后id 在auto_increment下仍会自增的解决办法

原文:https://www.cnblogs.com/waterserver/p/12236049.html

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