MySQL的自增ID并不一定连续

很多时候当我们给数据库表定义

1
id int auto_increment;

的时候可曾有的期待是这个id会随着插入的数据增多连续递增。

然而,递增是没有问题的,但是连续性其实并不能得到保证。

举个例子,在Gorm中,有相关Upsert的用法如下。

1
2
3
db.Clauses(clause.OnConflict{
UpdateAll: true,
}).Create(&users)

这样其实在Mysql中会被映射成on duplicate的语句,这个时候本来预约给新的record的id就被消耗了一个,所以如果这次成了更新没有插入,那么这个id就被跳过了。

更多其他参考

The only guarantees from an auto_increment column (or IDENTITY in MSSQL, and the other names the concept goes by) is that each value will be unique and never smaller than a previous one: so you can rely on the values for ordering but you can not rely on them not to have gaps.
引用