如何更改数据库中的所有表以使用AUTO_INCREMENT = 1

Ibr*_*mar 2 mysql database

我的数据库中有大约30个表:

table1 table2 table3 table4 table5 等等

我想要使​​用所有表AUTO_INCREMENT=1,如何修改表?

以下是其中一个表的示例DDL.我从未AUTO_INCREMENT在任何表中定义,默认情况下它是获取值.

CREATE TABLE `amenities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
Run Code Online (Sandbox Code Playgroud)

Dev*_*oot 5

要更改要用于新行的AUTO_INCREMENT计数器的值,请执行以下操作:

ALTER TABLE `table_name` AUTO_INCREMENT = 1;
Run Code Online (Sandbox Code Playgroud)

要更新所有31个表,您可以使用此php脚本:

<?php
$tables = array('table1','table2','tableX'); //continue here
foreach($tables as $update)
{
     mysql_query("ALTER TABLE `".$update."` AUTO_INCREMENT = 1;");
}
?>
Run Code Online (Sandbox Code Playgroud)

  • 是的,但这就是他们邀请复制/粘贴的内容.:) (2认同)

Nic*_*ssu 5

select concat('alter table ',table_name,' auto_increment = 1;') 
from information_schema.tables
where table_schema = 'your_db';
Run Code Online (Sandbox Code Playgroud)

然后运行生成的输出.顺便说一句,这是一个奇怪的问题.如果使用truncate table_nameauto_increment值将从1重新启动.

编辑.您可以使用out outfile在txt文件中重定向查询,然后调用它.

select concat('alter ',table_name,' auto_increment = 1;') 
into outfile 'd:/queries.txt'
lines terminated by '\r\n'
from information_schema.tables
where table_schema = 'your_db'
Run Code Online (Sandbox Code Playgroud)