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

时间:2011-06-05 11:35:59

标签: 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 ;

2 个答案:

答案 0 :(得分:5)

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

ALTER TABLE `table_name` AUTO_INCREMENT = 1;

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

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

答案 1 :(得分:5)

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

然后运行生成的输出。 顺便说一句,这是一个奇怪的问题。如果使用truncate table_name,则auto_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'
相关问题