Alter AUTO_INCREMENT value by select result

喜欢而已 提交于 2019-12-10 21:17:08

问题


Basically what I want is a working-version of the following code:

ALTER TABLE table_name
AUTO_INCREMENT =
(
    SELECT
        `AUTO_INCREMENT`
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_SCHEMA = 'database_name'
    AND TABLE_NAME = 'another_table_name'
);

The error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AUTO_INCREMENT =

The reason:

According to MySQL Doc:

InnoDB uses the in-memory auto-increment counter as long as the server runs. When the server is stopped and restarted, InnoDB reinitializes the counter for each table for the first INSERT to the table, as described earlier.

This means that whenever I restart the server, my auto_increment values are set to the minimum possible.

I have a table called ticket and another one called ticket_backup. Both of them have a column id that is shared. Records inside the ticket table are available and can be claimed by customers. When they claim the ticket I insert the record inside ticket_backup and then I erase them from ticket table. As of today, I have 56 thousand tickets already claimed (inside ticket_backup) and 0 tickets available. If I restart the server now and don't perform the ALTER TABLE, the first ticket I make available will have id 1 which is an ID already taken by ticket_backup, thus causing me duplicate key error if I don't fix the auto-increment value. The reason for me to want this in a single query is to be able to easily perform the query on server startup.


回答1:


Try this:

SELECT `AUTO_INCREMENT` INTO @AutoInc
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'another_table_name';

SET @s:=CONCAT('ALTER TABLE `database_name`.`table_name` AUTO_INCREMENT=', @AutoInc);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;



回答2:


Just upon quick glance, the error says it all. Syntax is incorrect

The syntax should adhere to:

ALTER TABLE table_name AUTO_INCREMENT=<INTEGER_VALUE>;

So looking at your query, remove the word "SET"

ALTER TABLE table_name AUTO_INCREMENT =
(
    SELECT
        `AUTO_INCREMENT`
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_SCHEMA = 'database_name'
    AND TABLE_NAME = 'another_table_name'
);



回答3:


What about

ALTER TABLE table_name 
SET AUTO_INCREMENT = (SELECT MAX(a.AUTO_INC_VAL) FROM database_name.table_name a) )

if you want the current increment value or

ALTER TABLE table_name 
SET AUTO_INCREMENT = (SELECT MIN(a.AUTO_INC_VAL) FROM database_name.table_name a) )

if you want the same initial INCREMENT VALUE



来源:https://stackoverflow.com/questions/27785379/alter-auto-increment-value-by-select-result

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