sql - 具有继承性的 PostgreSQL 外键

标签 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

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

我不知道如何创建此关联?

最佳答案

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/

相关文章:

sql - Azure SQL 查询突然触发数千次

java - JPA深度继承注解属性

java - 如何在抽象父类(super class)中使用子类的方法

sql - 传递一个对象(.net 或 json 对象)作为 postgresql 函数的输入参数

每行有多个子查询的Mysql查询

mysql - mysql中元素的总和

sql - 从 Hibernate 查询中的时间戳中提取时间

python - 使用 psycopg 时表格不会改变

sql - 检索具有列最大值的行的属性

通过 Object.create 从原始值继承 JavaScript 对象