带有继承的PostgreSQL外键

时间:2019-02-18 09:42:11

标签: sql postgresql inheritance

我有一个PostgreSQL数据库,3个表和如下所示的架构。 enter image description here

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;

enter image description here

现在,我想像这样在Table BTable C之间添加关联:

enter image description here

我不知道当我们继承同一个表时是否可能?

我看不到如何创建此关联?

1 个答案:

答案 0 :(得分:1)

您需要table_b上的唯一标识符或主键。引用文档:

  

除非使用NO INHERIT子句明确指定,否则父表的所有检查约束和非空约束都将由其子表继承。 其他类型的约束(唯一,主键和外键约束)不会被继承

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);

我更喜欢第一种方法,但我也出于学术目的发布了该方法。

相关问题