MySQL 跳过 auto_increment 个值

MySQL skipping auto_increment values

我的用户table只有3个字段

id (primary key, auto increment), 
username (not null, unique) and 
password(not null). 

当我尝试插入一个包含值“test”和“123”的行时,我得到了 1 作为主键,然后我再次尝试使用相同的值,并且我得到了键“username”的重复条目,正如预期的那样,然后我尝试使用“test1”和“123”,我得到了 3 作为主键,2 被跳过,为什么它显示这种行为。

MySQL 版本为 5.7.27.

这是一个documented behavior:

“Lost” auto-increment values and sequence gaps

In all lock modes (0, 1, and 2), if a transaction that generated auto-increment values rolls back, those auto-increment values are “lost”. Once a value is generated for an auto-increment column, it cannot be rolled back, whether or not the “INSERT-like” statement is completed, and whether or not the containing transaction is rolled back. Such lost values are not reused. Thus, there may be gaps in the values stored in an AUTO_INCREMENT column of a table.

在您的用例中,auto_increment 在检查 username 的唯一约束之前被分配了一个新值。然后约束检查失败,事务被回滚,在序列中留下一个间隙。

还有许多其他情况会导致 auto_increment 序列中出现间隙(例如,使用 INSERT ... IGNOREINSERT ... ON DUPLICATE KEY 语法时),这些情况本质上与隐式相关或事务的显式回滚。

底线:不要假设 aut_increment 键是连续的。保证的是唯一性,一定程度上保证了数量的增加。