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

在使用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
);

参考文章:

猜你喜欢

转载自www.cnblogs.com/waterserver/p/12236049.html