A beginners' question about foreign key in MySQL.
In w3school it says,
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
And also there is WHERE,
WHERE id = page_id
So if I can use WHERE for linking the tables, what is the main purpose of having foreign key?
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.
A Simplified Rule of Thumb is to put the foreign key on the child table (if each parent can have many children)*.
It's not strictly needed for the query, it's true. It exists for several reasons:
(1) is probably the important one of the three. This is called referential integrity. It means that if there is a value in a foreign key there will be a corresponding record with that value as a primary key in the parent table.
That being said, not all databases support referential integrity (eg MySQL/MyISAM tables) and those that do don't necessarily enforce it (for performance reasons).
The Foreign is used for referential integrity.
See An introduction to foreign keys and referential integrity in MySQL
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