删除时保留从 BIGSERIAL 创建的序列 table

Keep sequence created from BIGSERIAL when deleting table

我有一个 postgres table 使用以下 SQL 创建:

CREATE TABLE mytable (
    mytable_id BIGSERIAL NOT NULL,
    mytable_char VARCHAR(8) NOT NULL
)

这将创建 table 以及隐式 mytable_mytable_id_seq 序列。

现在,在创建 1.000.000 条记录后,我想将此 table 拆分为分区的 tables(使用继承)。因为我 link 从其他 table 中引用主 table,所以我想在新的子 table 中继续使用原始 table 中的 ID并继续使用序列。

但是,如果我这样做 DROP TABLE mytable,它也会删除序列。删除 table 时如何保持顺序?

您需要先解除列与序列之间的关联:

alter sequence mytable_mytable_id_seq owned by none;

如果您现在删除 table,序列将不会被删除。

手册中有详细说明:http://www.postgresql.org/docs/current/static/sql-altersequence.html

另一种方法是创建一个新序列并将其设置为现有序列的值:

create sequence part_seq;
select setval('part_seq', (select nextval('mytable_mytable_id_seq'), false);