MySQL:唯一索引冲突消耗主键 ID


#MySQL 笔记


如题。

示例

建表:

create table test_table (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name varchar(32) not null,
    PRIMARY KEY (`id`),
    UNIQUE KEY uk_name(`name`)
) engine = InnoDB character set = utf8mb4;

插入数据:

insert into test_table(name) values('aaa');
insert into test_table(name) values('aaa'); -- 会报错 Duplicate entry 'aaa' for key 'uk_name'
insert into test_table(name) values('bbb');

查询数据:

mysql> select * from test_table;
+----+------+
| id | name |
+----+------+
| 1  | aaa  |
| 3  | bbb  |
+----+------+
2 rows in set

可以看到 id 2 因为唯一索引冲突被消耗掉了。



( 本文完 )