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

Posted waterserver

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
);

参考文章:

以上是关于mysql insert操作失败后id 在auto_increment下仍会自增的解决办法的主要内容,如果未能解决你的问题,请参考以下文章

mysql插入数据后返回自增ID的方法(AUTO_INCREMENT)

获取 mysql(innodb) AUTO_INCREMENT Column、JDBC/getGeneratedKeys()/last_insert_id (in OkPacket) 和 LAST_I

mysql的执行insert是不是有返回值

MySQL :LAST_INSERT_ID()函数总结

在php连接数据库中,怎么获取某一个表的某个列的id号?

PHPmysql_insert_id() 函数