MYSQL & innoDB alter dynamically AUTO_INCREMENT of a table

时光总嘲笑我的痴心妄想 提交于 2019-12-13 13:04:07

问题


I have a problem, for example in my system I have the next table:

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

With content:

+-----+-------+
| id  | amount|
+-----+-------+
|2023  |  100 |
|2024  |  223 |
|2025  |  203 |
|...          |
|2505  |  324 |
+-----+-------+

I don't know the current id(There are sales every day). I'm trying to normalize the table.

UPDATE  sales SET id=id - 2022;

Result:

+-----+-------+
| id  | amount|
+-----+-------+
|   1  |  100 |
|   2  |  223 |
|   3  |  203 |
|...          |
| 482  |  324 |
+-----+-------+

The problem

My problem was trying to change the AUTO_INCREMENT, f.e.:

ALTER TABLE sales AUTO_INCREMENT = 483;

Its correct but I don't know the current id :(, I try the following query:

ALTER TABLE sales AUTO_INCREMENT = (SELECT MAX(id) FROM sales );

This causes me a error(#1064). Reading the documentation tells me:

In MySQL, you cannot modify a table and select from the same table in a subquery.

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

I try whit variables:

SET @new_index = (SELECT MAX(id) FROM sales );
ALTER TABLE sales AUTO_INCREMENT = @new_index;

But, this causes a error :(.


回答1:


ALTER TABLE must have literal values in it by the time the statement is parsed (i.e. at prepare time).

You can't put variables or parameters into the statement at parse time, but you can put variables into the statement before parse time. And that means using dynamic 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;



回答2:


Thanks to Bill Karwin, my query was:

SET @sales_init = 2022;
DELETE FROM `sales` WHERE `sales`.`id` <= @sales_init;
UPDATE  sales SET id=id - @sales_init;
-- set new index for sales
SET @new_init = (SELECT MAX(id) + 1 FROM sales );
SET @query = CONCAT("ALTER TABLE sales AUTO_INCREMENT =  ", @new_init);
PREPARE stmt FROM @query;
EXECUTE stmt;


来源:https://stackoverflow.com/questions/24439187/mysql-innodb-alter-dynamically-auto-increment-of-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!