gpt4 book ai didi

sql - 如何使用Postgres添加指向2个表之一的外键?

转载 作者:行者123 更新时间:2023-12-04 08:48:24 26 4
gpt4 key购买 nike

我想添加一个外键,用于检查记录或个人记录表之一中是否存在事件的记录 ID。可以用 Postgres 做吗?

CREATE TABLE record
(
id BIGSERIAL PRIMARY KEY
);

CREATE TABLE personal_record
(
id BIGSERIAL PRIMARY KEY
);

CREATE TABLE activity
(
id BIGSERIAL PRIMARY KEY,
record_id BIGINT NOT NULL,
CONSTRAINT record_fk FOREIGN KEY (record_id) REFERENCES record (id)
);

最佳答案

如前所述,这是不可能的。一种可能性是生成的列和可为空的引用:

CREATE TABLE activity (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
private_record_id BIGINT,
private_personal_record_id BIGINT,
record_id BIGINT GENERATED ALWAYS AS (COLAESCE(private_record_id, private_personal_record_id)),
CHECK( (private_record_id IS NOT NULL AND private_personal_record_id IS NULL) OR
(private_record_id IS NULL AND private_personal_record_id IS NOT NULL)
),
CONSTRAINT fk_activity_record_id FOREIGN KEY (private_record_id) REFERENCES record(id),
CONSTRAINT fk_activity_record_id FOREIGN KEY (private_personal_record_id) REFERENCES personal_record(id),
);
您可能还想研究继承。

关于sql - 如何使用Postgres添加指向2个表之一的外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64196259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com