Postgresql 使用约束将主键添加为串行

Postgresql add primary key as serial using contraint

我有一个 table,它有一个 Id 列作为 int 但没有作为主键提及。现在我想将主键约束添加为串行。我已经看到这个问题 但是这是使用 alter table 语句,而我的意图是在有约束的情况下这样做。有没有办法像下面那样做?

constraint "PK_tablename" serial primary key ("Id")

您可以在单个语句中添加约束和 identity 属性:

alter table the_table
    add constraint pk_the_table primary key (id),
    alter id add generated always as identity;

因为您的 table 中很可能已经有数据,您需要调整标识子句使用的序列:

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