mysql 插入失败了防止自增

所以我就在搜索下原因,发现是InnoDB的机制,大致就是说InnoDB的innodb_autoinc_lock_mode模式下,自增计数器在操作失败的情况下仍会增加。一般情况下如果担心id增加超过范围,可以把id的类型改为BIGINT。

 

插入一条记录

常规写法:

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

);

posted @ 2022-07-01 17:35  星云惊蛰  阅读(272)  评论(0)    收藏  举报