patternsqlModerate
Which table should a foreign key live on
Viewed 0 times
foreignliveshouldwhichtablekey
Problem
I'm learning about databases. In my very simple database, I have 2 tables.
and
As you can see, they currently do not relate.
Now, I'm faced with the question of making them relate. I understand I do this by adding a foreign key, something like MyOtherTableID and linking this to the other tables ID.
In the example above, I could add a foreign key to EITHER
with
OR
with
I've tried this, and it seems to work but by having this option frightens me. Is there a 'right' answer or will this change only affect the order in which data can be written to the database. If this is the case, then surely this will dictate the flow of the program using it (the users GUI).
WorkingHoursDetail
ID
NameOfWeek
Hoursand
WorkingHours
ID
NameAs you can see, they currently do not relate.
Now, I'm faced with the question of making them relate. I understand I do this by adding a foreign key, something like MyOtherTableID and linking this to the other tables ID.
In the example above, I could add a foreign key to EITHER
WorkingHoursDetail
ID
NameOfWeek
Hours
WorkingHoursIdwith
WorkingHours
ID
NameOR
WorkingHoursDetail
ID
NameOfWeek
Hourswith
WorkingHours
ID
Name
WorkingHoursDetailIdI've tried this, and it seems to work but by having this option frightens me. Is there a 'right' answer or will this change only affect the order in which data can be written to the database. If this is the case, then surely this will dictate the flow of the program using it (the users GUI).
Solution
As a rule of thumb, you should add a foreign key on the child table referencing the parent table. In your case it appears that
You can identify the parent table by asking which table can exists on its own without the presence of the other table. In your case
Alternatively you can look at the data flow when inserting new records. If both tables are empty, you should have to insert a row in
WorkingHoursDetail is the child table and WorkingHours the parent table. You can identify the parent table by asking which table can exists on its own without the presence of the other table. In your case
WorkingHours can exists without WorkingHoursDetails (but not the other way around, so WorkingHours appears to be the parent table. Alternatively you can look at the data flow when inserting new records. If both tables are empty, you should have to insert a row in
WorkingHours first and then a record in WorkingHoursDetail. This makes WorkingHours the parent table and therefore the foreign key should be added on WorkingHoursDetail referencing WorkingHours.Context
StackExchange Database Administrators Q#123169, answer score: 11
Revisions (0)
No revisions yet.