是否可以在 PG12 中为按日期范围分区的表创建 FK?
想象一下,我有一张大桌子user_session
和event
一张带有 FK 的桌子:
create table user_session( -- BIG TABLE to be partitioned
id bigserial primary key,
created_at timestamptz not null default now(),
some_info text
);
create table event(
id bigserial primary key,
user_id bigint references user_session (id), -- FK
data text
);
第一个想法是创建这样的新模式:
create table user_session(
id bigserial primary key,
created_at timestamptz not null default now(),
some_info text
) PARTITION BY RANGE (created_at);
但它失败并出现错误:
Detail: PRIMARY KEY constraint on table "user_session" lacks column "created_at" which is part of the partition key.
好的,让我们用两列进行PK:
create table user_session(
id bigserial,
created_at timestamptz not null default now(),
some_info text,
primary key (id, created_at)
) PARTITION BY RANGE (created_at);
但是,现在我无法创建表event
:
[42830] ERROR: there is no unique constraint matching given keys for referenced table "user_session"
。我也无法手动创建唯一约束。
在大多数 Postgres 文章中,分区表上都有没有 PK 的代码:
create table user_session(
id bigserial,
created_at timestamptz not null default now(),
some_info text,
) PARTITION BY RANGE (created_at);
但是,现在我无法创建event
表:
[42830] ERROR: there is no unique constraint matching given keys for referenced table "user_session"
这样做的正确方法是什么?