夜猫的小站

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

Published on
阅读时间:2分钟264

本文最近一次更新于 1919 个天前,其中的内容很可能已经有所发展或是发生改变。

前言

在使用 golang go-sql-driver 操作 mysql 时,往 tag 表插入一条新数据时,如果插入失败,id 仍会自增,插入数据失败次数过多时,id 就看起来十分混乱。

实现

所以我就在搜索下原因,发现是InnoDB的机制,大致就是说InnoDBinnodb_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
);

参考文章