我有一个 PostgreSQL 数据库、3 个表和我的架构如下。
CREATE TABLE table_a (
id SERIAL PRIMARY KEY,
name_a VARCHAR(255)
);
CREATE TABLE table_b (
name_b VARCHAR(255)
) INHERITS (table_a);
CREATE TABLE table_c (
name_c VARCHAR(255)
) INHERITS (table_a);
insert into table_b (name_a, name_b) values('table A','table B1');
insert into table_b (name_a, name_b) values('table A','table B2');
insert into table_c (name_a, name_c) values('table A','table C1');
insert into table_c (name_a, name_c) values('table A','table C2');
select * from table_a;
select * from table_b;
select * from table_c;
现在我想在 Table B
和 Table C
之间添加一个关联,如下所示:
我不知道当我们继承同一张表时这是否可能?
我不知道如何创建此关联?
最佳答案
table_b
需要一个唯一标识符或主键。引用文档:
All check constraints and not-null constraints on a parent table are automatically inherited by its children, unless explicitly specified otherwise with NO INHERIT clauses. Other types of constraints (unique, primary key, and foreign key constraints) are not inherited.
CREATE TABLE table_a (
id SERIAL PRIMARY KEY,
name_a VARCHAR(255)
);
CREATE TABLE table_b (
name_b VARCHAR(255),
primary key (id) --> here you set the PK
) INHERITS (table_a);
CREATE TABLE table_c (
name_c VARCHAR(255),
id_b int references table_b(id) --> the fk to b through pk
) INHERITS (table_a);
替代方式
在你的第二张图中,你有一种table_b
的标识符吗?这是正确的,因为您可以通过唯一字段引用表。在这种情况下,DDL 将是这样的:
CREATE TABLE table_a (
id SERIAL PRIMARY KEY,
name_a VARCHAR(255)
);
CREATE TABLE table_b (
name_b VARCHAR(255),
id_b SERIAL UNIQUE --> Here the unique id for b
--, primary key (id) -- optionally
) INHERITS (table_a);
CREATE TABLE table_c (
name_c VARCHAR(255),
id_b int references table_b(id_b) --> the fk to b through unique
) INHERITS (table_a);
我更喜欢第一种方法,但出于学术目的我也发布了这种方法。
关于sql - 具有继承性的 PostgreSQL 外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54744302/