2011-06-05 87 views
2

我在我的數據庫中約30桌:如何更改在我的數據庫中的所有表使用AUTO_INCREMENT = 1

table1table2table3table4table5

我希望所有的表使用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 ; 

回答

4

要更改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;"); 
} 
?> 
+0

我必須重複該代碼30次我所有的30個表嗎? – 2011-06-05 11:39:23

+2

是的,但這就是他們邀請複製/粘貼的內容。 :) – GolezTrol 2011-06-05 11:40:35

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重新開始。

編輯。您可以使用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' 
相關問題