【问题标题】:PostgreSQL add auto increment to empty ID columnPostgreSQL 将自动增量添加到空 ID 列
【发布时间】:2020-09-05 06:31:56
【问题描述】:

我在 PostgreSQL 中创建表,但我忘记添加 auto increment

如何更改 Postgres 中的空 Id 列以添加 auto increment

【问题讨论】:

  • PostgreSQL 中没有 AUTO INCREMENT 语法;您必须选择 SERIAL 或 IDENTITY。

标签: postgresql identity auto-increment


【解决方案1】:

从 Postgres 10 开始,建议为此使用 identity 列。

您可以使用 ALTER TABLE 将现有列转换为标识列:

alter table the_table
  alter id add generated always as identity;

如果表中已有数据,则需要同步序列:

select setval(pg_get_serial_sequence('the_table', 'id'), (select max(id) from the_table));

【讨论】:

    【解决方案2】:

    您需要创建该列拥有的序列并将其设置为默认值。

    例如

    CREATE TABLE mytable (id int);
    
    CREATE SEQUENCE mytable_id_seq OWNED BY mytable.id;
    
    ALTER TABLE mytable ALTER COLUMN id SET DEFAULT nextval('mytable_id_seq');
    

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 2013-01-23
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 2020-03-19
      • 2016-05-29
      相关资源
      最近更新 更多