在 postgres 的 alter table 语句中使用 select 的结果

Using result of select inside alter table statement in postgres

我有一个 postgres table 定义如下:

CREATE TABLE public.Table_1
(
  id bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 
  START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 )
) 

由于数据迁移,id 列混乱,在 INSERT 上生成的 id 值不唯一。因此,我需要重置 id 列如下

SELECT MAX(id) + 1 From Table_1;
ALTER TABLE Table_1 ALTER COLUMN id RESTART WITH 935074;

现在我 运行 第一个查询获取 Max(id) + 1 值,然后我需要在 ALTER 查询中替换它。 有没有办法存储 SELECT 的结果并只使用 ALTER 语句中的变量?

这是一种方法:

select setval(pg_get_serial_sequence('Table_1', 'id'), coalesce(max(id),0) + 1, false) 
from Table_1;

理由:

  • pg_get_serial_sequence() returns 给定 table 和列的序列名称
  • set_val()可用于重置序列
  • 这可以包含在 select 中,它为您提供 table 中 id 的当前最大值(如果 table 为空,则为 1)