2011-10-30 118 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将被重新分配;)