2011-10-30 73 views
6

我設置了一個數據庫,並且有一個自動遞增的列,這個列本來就是一個ID。問題是我忘了在phpMyAdmin中創建表格時檢查自動增量......並且直到現在才注意到!所以我有這樣的東西:MySQL:忘記設置自動遞增

ID | column one | column two 
------------------------------------ 
0 | some value | some value 
0 | other value | something else 
0 | example val. | something 
0 | my example | something 

基本上,我的「自動遞增」列顯示零板。我如何修改此表以顯示所有以前和所有未來行的自動增量?

+1

您有表的模式? –

回答

8

如果表是空的,你可能只是這樣做:

ALTER TABLE mytable MODIFY COLUMN id bigint not null primary key auto_increment 

,但我不知道會在這行發生什麼。最好使用正確的定義創建一個新的數據庫,通過減去id列來複制數據,刪除舊的(錯誤的)表格,並將新數據移動到舊名稱。

-- Either: 
CREATE TABLE newtable LIKE mytable; 
ALTER TABLE newtable MODIFY COLUMN id bigint not null primary key auto_increment; 
-- or: 
CREATE TABLE newtable (
    id bigint not null primary key auto_increment, 
    column1 type1, 
    column2 type2, 
    ... 
); 

INSERT INTO newtable 
    (column1, column2, ...) 
    SELECT column1, column2, column3, ... 
    FROM mytable; 
-- Make SURE that insert worked BEFORE you drop the old table 
-- and lose data if it didn't. 
DROP TABLE mytable; 
ALTER TABLE newtable RENAME TO mytable; 

我相信phpMyAdmin有能力以圖形方式做到這一點。

+0

是的,這將工作。只需將該列修改爲「PRIMARY KEY」和「auto_increment」即可。 –

+1

+1良好的解決方案,如果你有很多記錄 –

6

首先更新您的記錄(否則你會得到重複的主鍵):

UPDATE `tablename` SET id = 1 WHERE "column one" = 'some value'; 
UPDATE `tablename` SET id = 2 WHERE "column one" = 'other value'; 
UPDATE `tablename` SET id = 3 WHERE "column one" = 'example val.'; 
UPDATE `tablename` SET id = 4 WHERE "column one" = 'my example'; 

然後添加主鍵/ AUTO_INCREMENT:

ALTER TABLE tablename MODIFY COLUMN id int(11) NOT NULL primary key auto_increment; 

然後設置下一個AUTO_INCREMENT:

ALTER TABLE tablename AUTO_INCREMENT = 5; 
+0

如果有多條線路,更新所有記錄將非常緩慢和勞動密集型。 – Kevin

+0

我同意,但在這個例子中有4條記錄。如果用戶有很多記錄,我就投了你的票 –

4

您可以刪除ID列並重新創建它。如果您記住啓用自動增量,則ID將被重新分配;)