简体   繁体   中英

PostgreSQL foreign key with inheritance

I have a PostgreSQL database, 3 tables and my schema as follows. 在此输入图像描述

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;

在此输入图像描述

Now i want to add an association between Table B and Table C like this:

在此输入图像描述

I do not know if this is possible when we inherit the same table ?

I do not see how I can create this association ?

You need a unique identifier or primary key on table_b . Quoting docs:

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

Alternative way

In your second diagram, do you have a kind of identifier for table_b . It is right because you can reference table by a unique field. In this case, the DDL will be like this:

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

I prefer the first approach, but I have posted also this one just for academical purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM