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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With