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
);

參考文章:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM