在使用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
);
參考文章: