【发布时间】:2020-05-26 20:18:14
【问题描述】:
我一直在尝试在 postgresql v12 中引用分区表,但遇到了问题。
这些表在日期列上由range 分区,每个分区的值是月份分隔符(例如:FOR VALUES FROM ('2020-04-01T00:00:00') TO ('2020-05-01T00: 00:00'))
我有 2 张桌子:
Table A
Column | Type | Collation | Nullable | Default
-----------------+--------------------------+-----------+----------+---------
uuid | character varying(36) | | not null |
start_date | timestamp with time zone | | not null |
Partition key: RANGE (start_date)
Indexes:
"table_a_pkey" PRIMARY KEY, btree (uuid, start_date)
Table B
Column | Type | Collation | Nullable | Default
-----------------+--------------------------+-----------+----------+---------
uuid | character varying(36) | | not null |
start_date | timestamp with time zone | | not null |
ref_a_id | character varying(36) | | not null |
Partition key: RANGE (start_date)
Indexes:
"table_b_pkey" PRIMARY KEY, btree (uuid, start_date)
向分区表添加主键时,我知道必须包含分区键。但是,table_a.start_date 和 table_b.start_date 并不完全匹配,通常只有两个日期的月份应该匹配,当然,ref_a_id 到 uuid。
到目前为止,这是我尝试过的:
ALTER TABLE table_a ADD CONSTRAINT ref_fk FOREIGN KEY (ref_a_id) REFERENCES table_b (uuid) DEFERRABLE INITIALLY DEFERRED;
-> ERROR: there is no unique constraint matching given keys for referenced table "table_b"
ALTER TABLE table_a ADD CONSTRAINT ref_fk FOREIGN KEY (ref_a_id) REFERENCES table_b DEFERRABLE INITIALLY DEFERRED;
-> ERROR: number of referencing and referenced columns for foreign key disagree
ALTER TABLE table_a ADD CONSTRAINT ref_fk FOREIGN KEY (ref_a_id, start_date) REFERENCES table_b (uuid, start_date) DEFERRABLE INITIALLY DEFERRED;
后者有效,但在导入时我得到了
-> ERROR: insert or update on table "table_b" violates foreign key constraint "ref_fk"
DETAIL: Key (ref_a_id, start_date)=(XXXXX-XXXXX-XXXXX-XXXXX, 2020-05-27 01:32:13+00) is not present in table "table_a".
我现在看到的唯一解决方案是添加一个新列year_month,其值类似于2020_04,并在这个新列上按list 进行分区。因此引用应该匹配。
还有其他解决方案吗?有没有办法我可以只引用 start_date 列的月份而不是添加新列?甚至可能只引用table_a.uuid?
【问题讨论】:
标签: postgresql reference foreign-keys partitioning postgresql-12