Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deciding on foreign key while implementing one to one relationship in MySQL

Tags:

I have two simple tables "items" and "orders". For the sake of simplicity lets assume that one item can only be in one order or one order can only contain one item.

Now as this can be implemented using simple one to one relationship I can do following:

I can add the primary key of the orders table to the items table like below

//Table Items item_id, item_name, order_id 1,        shoes,    1 2,        watch,    2  //Table Orders order_id, customer 1,        James 2,        Rick 

or I can add the primary key of the items table to the orders table like below

//Table Items     item_id, item_name     1,        shoes     2,        watch  //Table Orders order_id, customer, item_id 1,        James,    1    2,        Rick,     2 

Which one is correct and why? Are there any guide lines to decide which key goes where? Sure common sense will work in simple examples as above but in complex examples how do we decide?

like image 596
Jay Bhatt Avatar asked May 31 '13 18:05

Jay Bhatt


People also ask

Do you need a foreign key in a one-to-one relationship?

If there is a one-to-one relationship between one entity and another entity, add the key of one of the entities into the table for the other entity, thus changing it to a foreign key. The addition of a foreign key due to a one-to-one relationship can be made in either direction.

What role does a foreign key play in implementing a relationship?

Foreign keys put the “relational” in “relational database” – they help define the relationship between tables. They allow developers to maintain referential integrity across their database.

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

Whichever one is not the primary key is the foreign key. In one-to-many relationships, the FK goes on the "many" side. It can't go on the "one" side because that's where the PK goes and the definition of a primary key includes disallowing duplicates.

How do you choose a foreign key?

A Foreign Key is a database key that is used to link two tables together. The FOREIGN KEY constraint identifies the relationships between the database tables by referencing a column, or set of columns, in the Child table that contains the foreign key, to the PRIMARY KEY column or set of columns, in the Parent table.


1 Answers

One-to-One relationships should be generally merged simply into one table. If there aren't any contradictions, the One-to-One relationship might be a sign of an unconsidered decision.

And If You really want to use this kind of relationship, it's totally up to You where to place FK. You might want to take optionality into consideration when applying FK. However, in MySQL, it still won't be a true One-to-One relationship because deferred keys are not supported there.

like image 91
Grzegorz Piwowarek Avatar answered Oct 20 '22 20:10

Grzegorz Piwowarek