3

I have a PostgreSQL database, 3 tables and my schema as follows. 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

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

enter image description here

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

I do not see how I can create this association ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

my column id_b of my Table C is null
@Mercer, thanks about your comments. I improved my answer. Also, you can found an example with FK here: db-fiddle.com/f/kG1Vxo8jMWsNsVRvREfapr/0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.