Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I store a foreign key?

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?

like image 873
vicatcu Avatar asked Jul 20 '10 19:07

vicatcu


People also ask

Where do you store foreign keys?

Foreign key references are stored within a child table and links up to a primary key in a separate table. The column acting as a foreign key must have a corresponding value in its linked table.

Which table does the foreign key go in?

The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.

Where does the foreign key go in a many to many relationship?

In a many-to-many relationship, a row in table A can have many matching rows in table B, and vice versa. You create such a relationship by defining a third table that is called a junction table. The primary key of the junction table consists of the foreign keys from both table A and table B.

Where should the foreign key be placed when 1 to n relationship exists between entities?

either the parent table or the child table.


2 Answers

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.

like image 97
OMG Ponies Avatar answered Oct 07 '22 13:10

OMG Ponies


"What is a systematic way of making that decision though?"

There appear to be two choices: The "One" side as FK's to the "Many side", or the "Many" Side has FK's to the "One" side.

Let's actually look a the choices.

  • All the rows of the "Many" side can easily reference one row on the "One" side.

  • The one row on the "One" side cannot ever reference ALL of the rows on the "Many" side.

Only one technique works: "Many" side has FK to "One" side.

There is only one actual implementation choice. There's no "decision".

like image 38
S.Lott Avatar answered Oct 07 '22 15:10

S.Lott