自增主鍵沒有持久化是個比較早的bug,這點從其在官方bug網站的id號也可看出(https://bugs.mysql.com/bug.php?id=199)。由Peter Zaitsev(現Percona CEO)於2003年提出。歷史悠久且臭名昭著。 php
首先,直觀的重現下。mysql
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)
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)
SELECT MAX(ai_col) FROM table_name FOR UPDATE;
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 ;