MySQL 跳过 auto_increment 值

标签 mysql sql database database-design auto-increment

在我的用户表中只有 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 ... IGNOREINSERT ... ON DUPLICATE KEY 语法时),本质上与事务的隐式或显式回滚有关。

底线:不要假设 aut_increment 键是连续的。保证的是唯一性,并在某种程度上保证数量不断增加。

关于MySQL 跳过 auto_increment 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59047101/

相关文章:

database - SqlCeConnection 实例耗时过长

mysql - 加速包含 100K+ 记录的 MYSQL 左连接查询

php - 这个 Mysql select,php 代码有什么问题?

mysql - 选择同一表中用户支付订单的计数

sql - 跳过/忽略/不插入重复行

mysql - 数据库设计 - 将列中的数据加倍

mySQL - 选择前 n 行,按 2 列分组

mysql - 插入没有 id postgreSQL 的命令

mysql - 数据库连接失败: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

php mysql - phpmyadmin 日期