PostgreSQL 分区和唯一冲突

PostgreSQL Partition and Unique Conflict

我正在尝试设置带分区的数据库,但是在创建 activity table 时我 运行 出错了。 3 Table CREATE(不含实际数据)如下:

CREATE TABLE collection (
    id SERIAL PRIMARY KEY
);


CREATE TABLE asset (
    id SERIAL,
    collection_id INT,
    CONSTRAINT fk_collection
        FOREIGN KEY(collection_id)
            REFERENCES collection(id),
    CONSTRAINT asset_pkey PRIMARY KEY(id, collection_id)
)PARTITION BY LIST(collection_id);


CREATE TABLE activity(
    id SERIAL,
    collection_id INT,
    CONSTRAINT fk_collection
        FOREIGN KEY(collection_id)
            REFERENCES collection(id),
    CONSTRAINT activity_pkey PRIMARY KEY(id, collection_id),
    asset_id INT,
    CONSTRAINT fk_asset
        FOREIGN KEY(asset_id)
            REFERENCES asset(id)
) PARTITION BY LIST(collection_id);

ERROR:  there is no unique constraint matching given keys for referenced table "asset"
SQL state: 42830

我的错误理解是外键必须是唯一的。因为我必须添加 collection_id 作为分区项的主键,所以我不能将 id 也指定为唯一的。当我尝试使 id 唯一时,会发生以下情况:

ALTER TABLE asset
    ADD CONSTRAINT u_id UNIQUE (id);

ERROR:  unique constraint on partitioned table must include all partitioning columns
DETAIL:  UNIQUE constraint on table "asset" lacks column "collection_id" which is part of the partition key.
SQL state: 0A000

即使我成功地在 id 和 collection_id 上添加了 UNIQUE 约束,它仍然会抛出 SQL 状态:42830。我是否必须重组我的数据或者是否有更好的方法来去做我没想到的事?

asset 上的外键合并到一个复合键中是否足够,或者这是否违反了您的数据的某些其他约束?

CREATE TABLE activity(
    id SERIAL,
    collection_id INT,
    asset_id INT,
    CONSTRAINT activity_pkey PRIMARY KEY(id, collection_id),
    CONSTRAINT fk_asset_collection
        FOREIGN KEY(asset_id, collection_id)
            REFERENCES asset(id, collection_id)
) PARTITION BY LIST(collection_id);