I'm designing a PostgreSQL database schema where I need to establish a composite foreign key that references various tables based on an ENUM
value stored in another column. In main_table
has columns target_id
and target_type
. target_type
column holds values from an ENUM
type ('TYPE_A'
, 'TYPE_B'
and 'TYPE_C'
).
My objective is to create a composite foreign key that links to distinct tables (table_a
, table_b
and table_c
) based on target_type
. For instance, when target_type
is 'TYPE_A'
I aim for target_id
to function as a foreign key pointing to id
column in table_a
. Something like this (but this example doesn't work):
ALTER TABLE main_table
ADD CONSTRAINT fk_main_table_target_a
FOREIGN KEY (target_id, target_type)
REFERENCES table_a (id, 'TYPE_A');
How to implement this dynamic foreign key setup using PostgreSQL? Could someone provide me with a detailed example of creating such a composite foreign key, ideally with an ENUM value-based selection?