I have two tables, we’ll call them Foo and Bar, with a one to many relationship where Foo is the parent of Bar. Foo’s primary key is an integer automatically generated with a sequence.
Since Bar is fully dependent on Foo how would I setup the primary key of Bar given the following constraints:
- Records for Bar are programatically generated so user input can not be relied upon for an identifier.
- Multiple processes are generating Bar records so anything involving a
Select Max()to generate anIDwould present a race condition.
I have come up with two possible solutions that I am not happy with:
- Treat the tables as if they are a many to many relationship with a third table that maps their records together and have the application code handle inserting records so that the mapping between the records is created correctly. I don’t like this as it makes the database design misleading and errors in application code could result in invalid data.
- Give Bar two colunms:
FooIDandFooBarIDand generate a value forFooBarIDby selecting themax(FooBarID)+1for someFooID, but as previously stated this creates a race condition.
I appreciate any ideas for an alternative table layout.
Give Bar an automatic primary key the same as with Foo. Add a foreign key FooID column to Bar.
Unless I’m missing something, there doesn’t seem to be a reason why it wouldn’t work.