【问题标题】:MySQL: Forgot to set Auto IncrementMySQL:忘记设置自动增量
【发布时间】:2011-12-18 09:29:30
【问题描述】:

我设置了一个数据库,其中包含一个自动递增的列,该列是一个 ID。问题是我在phpMyAdmin中创建表时忘记检查自动增量......直到现在才注意到!所以我所拥有的是这样的:

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

基本上,我的“自动递增”列全面显示零。如何修改此表以显示所有先前和所有未来行的自动增量?

【问题讨论】:

  • 你有表的架构?

标签: mysql auto-increment


【解决方案1】:

如果桌子是空的,你可以这样做:

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 有能力以更图形化的方式做到这一点。

【讨论】:

  • 是的,这会起作用。只需将列修改为PRIMARY KEYauto_increment
【解决方案2】:

首先更新你的记录(否则你会得到重复的主键):

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;

【讨论】:

  • 如果超过几行,更新所有记录将非常缓慢且劳动密集。
  • 我同意,但在示例中,有 4 条记录。如果用户有很多记录,我投了你的票
【解决方案3】:

您可以删除 ID 列并重新创建它。如果您记得启用自动增量,则 ID 将被重新分配;)

【讨论】:

    猜你喜欢
    • 2011-03-06
    • 2017-09-16
    • 2012-11-30
    • 2013-10-04
    • 2011-11-25
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    相关资源
    最近更新 更多