在我的用户表中只有 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.
在您的用例中,在检查 username
的唯一约束之前,auto_increment 被分配了一个新值。然后约束检查失败,事务被回滚,在序列中留下空隙。
还有许多其他情况会导致 auto_increment 序列中出现间隙(例如,当使用 INSERT ... IGNORE
或 INSERT ... ON DUPLICATE KEY
语法时),本质上与事务的隐式或显式回滚有关。
底线:不要假设 aut_increment 键是连续的。保证的是唯一性,并在某种程度上保证数量不断增加。
关于MySQL 跳过 auto_increment 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59047101/