Where should I store a foreign key?

vicatcu picture vicatcu · Jul 20, 2010 · Viewed 16.7k times · Source

If I have a relationship between two tables (both tables have their own primary keys) what should guide my decision as to which table should store the foreign key? I understand that the nature of the relationship probably matters (one-to-one, one-to-many, many-to-many, uni-directional, bi-directional), and probably access patterns matter too. What is a systematic way of making that decision though?

Answer

OMG Ponies picture OMG Ponies · Jul 20, 2010

Which table is the child in the relationship?
Answer that, and you know which table needs the foreign key column, referencing the parent's [typically] primary key. That's for a one-to-many relationship...

A many-to-many would require you to add a third table, using the keys from both of the two tables as it's primary key.