简体   繁体   English

MYSQL和innoDB动态地改变表的AUTO_INCREMENT

[英]MYSQL & innoDB alter dynamically AUTO_INCREMENT of a table

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). 我不知道当前的id(每天都有销售)。 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 , fe: 我的问题是试图改变AUTO_INCREMENT ,fe:

ALTER TABLE sales AUTO_INCREMENT = 483;

Its correct but I don't know the current id :(, I try the following query: 它的正确,但我不知道当前的id :(,我尝试以下查询:

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

This causes me a error(#1064). 这导致我错误(#1064)。 Reading the documentation tells me: 阅读文档告诉我:

In MySQL, you cannot modify a table and select from the same table in a subquery. 在MySQL中,您无法修改表并从子查询中的同一个表中进行选择。

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

I try whit variables: 我尝试使用whit变量:

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

But, this causes a error :(. 但是,这会导致错误:(。

ALTER TABLE must have literal values in it by the time the statement is parsed (ie at prepare time). 在解析语句时(即在准备时), ALTER TABLE必须具有文字值。

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: 这意味着使用动态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;

Thanks to Bill Karwin , my query was: 感谢Bill Karwin ,我的疑问是:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM