I have a Postgres database, and it has a Foo
table and a Foo_Group
table. It also has a Bar
table, and all of these tables have a simple id
primary key column.
I'd like to create a many-to-many relationship between the three, such that a Bar
can have 0+ Foo
s and 0+ Foo_Group
s. I can create a Foo_and_Foo_Groups_Bar
JOIN table easily enough, with foreign keys to Foo
, Foo_Group
, and Bar
. However, I'm having trouble creating the primary key on my JOIN table.
The problem is, in Foo_and_Foo_Groups_Bar
either foo_id
or foo_group_id
will always be NULL
... but primary key columns can't have NULL
s. The only solution I've been able to find is to put an id
column on Foo_and_Foo_Groups_Bar
... but I thought JOIN tables weren't supposed to have their own ID, and were supposed to use their JOIN ID columns as the primary key.
So what is "correct" here? Do I add a (seemingly unnecessary, except to make the constraint happy) column to my JOIN table, or is there a better way?
I am a fan of synthetic primary keys. You can add a serial
/ generated always as identity
column for a primary key. And then add a unique constraint for the triplet of ids.
I'm not 100% sure from your example that you are talking about a single relationship. It sounds like you have two relationships, one between bar
and foo
and another between bar
and foo_groups
. If that is the case, then you can have two bridge tables and don't have to worry about NULL
values.
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.