自增主键没有持久化是个比较早的 bug,这点从其在官方 bug 网站的 id 号也可看出(https://bugs.mysql.com/bug.php?id=199)。由 Peter Zaitsev(现 Percona CEO)于 2003 年提出。历史悠久且臭名昭著。
首先,直观的重现下。
mysql> create table t1(id int auto_increment primary key);
Query OK, 0 rows affected (0.01 sec)
mysql> insert into t1 values(null),(null),(null);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0
mysql> select * from t1;
+—-+
| id |
+—-+
|  1 |
|  2 |
|  3 |
+—-+
3 rows in set (0.00 sec)
mysql> delete from t1 where id=3;
Query OK, 1 row affected (0.36 sec)
mysql> insert into t1 values(null);
Query OK, 1 row affected (0.35 sec)
mysql> select * from t1;
+—-+
| id |
+—-+
|  1 |
|  2 |
|  4 |
+—-+
3 rows in set (0.01 sec)
虽然 id 为 3 的记录删除了,但再次插入 null 值时,并没有重用被删除的 3,而是分配了 4 。
删除 id 为 4 的记录,重启资料库,重新插入一个 null 值。
mysql> delete from t1 where id=4;
# service mysqld restart
mysql> insert into t1 values(null);
Query OK, 1 row affected (0.00 sec)
mysql> select * from t1;
+—-+
| id |
+—-+
|  1 |
|  2 |
|  3 |
+—-+
3 rows in set (0.00 sec)
可以看到,新插入的 null 值分配的是 3,按照重启前的操作逻辑,此处应该分配 5 啊。
这就是自增主键没有持久化的 bug 。究其原因,在于自增主键的分配,是由 InnoDB 资料字典内部一个计数器来决定的,而该计数器只在内存中维护,并不会持久化到磁碟中。当资料库重启时,该计数器会通过下面这种方式初始化。
SELECT MAX(ai_col) FROM table_name FOR UPDATE;
MySQL 8.0 的解决思路
将自增主键的计数器持久化到 redo log 中。每次计数器发生改变,都会将其写入到 redo log 中。如果资料库发生重启,InnoDB 会根据 redo log 中的计数器资讯来初始化其内存值。为了尽量减小对系统效能的影响,计数器写入到 redo log 中,并不会马上重新整理。具体可参考:https://dev.mysql.com/worklog/task/?id=6204
因自增主键没有持久化而出现问题的常见场景:
1. 业务将自增主键作为业务主键,同时,业务上又要求主键不能重复。
2. 资料会被归档。在归档的过程中有可能会产生主键冲突。
所以,强烈建议不要使用自增主键作为业务主键。刨除这两个场景,其实,自增主键没有持久化的问题并不是很大,远没有想象中的” 臭名昭著 “。
最后,给出一个归档场景下的站群解决方案,
建立一个储存过程,根据 table2(归档表)自增主键的最大值来初始化 table1(线上表)。这个储存过程可放到 init_file 引数指定的档案中,该档案中的 SQL 会在资料库启动时执行。
DELIMITER ;;
CREATE PROCEDURE `auto_increment_fromtable2`(IN table1 VARCHAR(255), IN table2 VARCHAR(255))
BEGIN
set @qry = concat(‘SELECT @max1 := (`id` + 1) FROM `’,table1,’` ORDER BY `id` DESC LIMIT 1;’);
prepare stmt from @qry;
execute stmt;
deallocate prepare stmt;
set @qry = concat(‘SELECT @max2 := (`id` + 1) FROM `’,table2,’` ORDER BY `id` DESC LIMIT 1;’);
prepare stmt from @qry;
execute stmt;
deallocate prepare stmt;
IF @max1 < @max2 THEN set @qry = concat(‘alter table `’,table1,’` auto_increment=’,@max2);prepare stmt from @qry;execute stmt;deallocate prepare stmt; SELECT ‘updated’ as `status`; else SELECT ‘no update needed’ as `status`; END IF; END ;; DELIMITER ;