MYSQL和innoDB动态地改变表的AUTO_INCREMENT

fit*_*rec 6 mysql innodb auto-increment mysql-5.7

我有一个问题,例如在我的系统中我有下一个表:

CREATE TABLE `sales` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `amount` FLOAT NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;
-- is more complex table
Run Code Online (Sandbox Code Playgroud)

内容:

+-----+-------+
| id  | amount|
+-----+-------+
|2023  |  100 |
|2024  |  223 |
|2025  |  203 |
|...          |
|2505  |  324 |
+-----+-------+
Run Code Online (Sandbox Code Playgroud)

我不知道当前的id(每天都有销售).我正在尝试规范化表格.

UPDATE  sales SET id=id - 2022;
Run Code Online (Sandbox Code Playgroud)

结果:

+-----+-------+
| id  | amount|
+-----+-------+
|   1  |  100 |
|   2  |  223 |
|   3  |  203 |
|...          |
| 482  |  324 |
+-----+-------+
Run Code Online (Sandbox Code Playgroud)

问题

我的问题是试图改变AUTO_INCREMENT,fe:

ALTER TABLE sales AUTO_INCREMENT = 483;
Run Code Online (Sandbox Code Playgroud)

它的正确,但我不知道当前的id :(,我尝试以下查询:

ALTER TABLE sales AUTO_INCREMENT = (SELECT MAX(id) FROM sales );
Run Code Online (Sandbox Code Playgroud)

这导致我错误(#1064).阅读文档告诉我:

在MySQL中,您无法修改表并从子查询中的同一个表中进行选择.

http://dev.mysql.com/doc/refman/5.7/en/subqueries.html

我尝试使用whit变量:

SET @new_index = (SELECT MAX(id) FROM sales );
ALTER TABLE sales AUTO_INCREMENT = @new_index;
Run Code Online (Sandbox Code Playgroud)

但是,这会导致错误:(.

Bil*_*win 22

ALTER TABLE 在语句被解析时(即在准备时),它必须具有文字值.

你不能把变量或参数到语句在分析时,但你可以把变量到语句之前解析时间.这意味着使用动态SQL:

SET @new_index = (SELECT MAX(id) FROM sales );
SET @sql = CONCAT('ALTER TABLE sales AUTO_INCREMENT = ', @new_index);
PREPARE st FROM @sql;
EXECUTE st;
Run Code Online (Sandbox Code Playgroud)