数据库
首页 > 数据库> > mysql – 选择结果改变AUTO_INCREMENT值

mysql – 选择结果改变AUTO_INCREMENT值

作者:互联网

基本上我想要的是以下代码的工作版本:

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

错误:

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 =

原因:

根据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.

这意味着每当我重新启动服务器时,我的auto_increment值都会设置为尽可能小的值.

我有一个名为ticket的表,另一个名为ticket_backup.它们都有一个共享的列id.票证表内的记录可供客户索取.当他们声明票证时,我在ticket_backup中插入记录,然后从票证表中删除它们.截至今天,我已经声明了56000张门票(在ticket_backup内)和0张门票.如果我现在重新启动服务器并且不执行ALTER TABLE,我提供的第一张票将具有id 1,这是ticket_backup已经占用的ID,因此如果我不修复自动增量,则会导致重复键错误值.我想在单个查询中使用它的原因是能够在服务器启动时轻松执行查询.

解决方法:

试试这个:

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;

标签:sql,mysql,select,auto-increment,alter-table
来源: https://codeday.me/bug/20190725/1528983.html