postgresql 在postgres中更改表以添加“分区范围”

bjg7j2ky  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(344)

我想修改表,增加分区范围存档日期

CREATE TABLE transactions(
    id              UUID         not null ,
    txn_id          UUID         NOT NULL,
    orderId         UUID         NOT NULL,
    inserttstmp     timestamp    not NULL
    archivedate     timestamp    NULL
)

通常,每当我创建新表与分区与下面的脚本.但现在希望对现有表执行相同的操作。

CREATE TABLE attachment(
    id              UUID            not null,
    txn_id          UUID         NOT NULL,
    attachment_id   UUID         NOT NULL,
    inserttstmp     timestamp    not NULL
    archivedate     timestamp    NULL
)PARTITION BY RANGE (archivedate);

CREATE TABLE ins_txn_attachment_live PARTITION OF ins_txn_attachment DEFAULT;
ALTER  TABLE ins_txn_attachment_live ADD CHECK (archivedate is null);
ALTER  TABLE ins_txn_attachment_live ADD CONSTRAINT PK_INS_TXN_ATTACHMENT_EVENT_Live unique (id);

CREATE UNIQUE NONCLUSTERED INDEX PK_Ins_TXN_Attachment_ID_ArchiveData ON ins_txn_attachment (id,archivedate);

谢了,贾伽迪什

33qvvth1

33qvvth11#

通过查询,我相信您希望在现有表更改或添加分区列,在本例中为ins_txn_attachment_live。当没有为特定属性更改表的选项(如分区或更改表中字段的位置)时,我看到并亲自遵循的一种简单方法如下:
首先重命名你的表,并包括键或索引(此外,不要在PostgreSQL索引中给予PK前缀,因为PostgreSQL创建了开箱即用的主键索引,而不会在PGAdmin中可见):

ALTER TABLE ins_txn_attachment_live RENAME TO ins_txn_attachment_live_old
ALTER INDEX PK_Ins_TXN_Attachment_ID_ArchiveDataRENAME TO PK_Ins_TXN_Attachment_ID_ArchiveData_old

然后使用所需的分区创建新表:

CREATE TABLE ins_txn_attachment_live (
    id              UUID         NOT NULL,
    attachment_id   UUID         NOT NULL,
    inserttstmp     timestamp    not NULL
    archivedate     timestamp    NULL
)PARTITION BY RANGE (<whatever column>);

然后将数据从_old表复制到新表(如果源列和目标列相同):

INSERT INTO ins_txn_attachment_live SELECT * FROM ins_txn_attachment_live_old

然后将数据从_old表复制到新表(如果源列和目标列不同):

INSERT INTO ins_txn_attachment_live (id, attachment_id, inserttstmp, archivedate, new_column) SELECT id, attachment_id, inserttstmp, archivedate, 'new_default_value' FROM ins_txn_attachment_live_old

希望有帮助

相关问题