Reputation: 81384
In an answer on Stack Overflow, I saw this code:
CREATE TABLE Favorites (
user_id INT NOT NULL,
movie_id INT NOT NULL,
PRIMARY KEY (user_id, movie_id),
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (movie_id) REFERENCES Movies(movie_id)
);
I've never used the 'foreign key' relationship keyword before.
Upvotes: 17
Views: 7708
Reputation: 670
You can also add the ability to cascade when a related record is deleted. For example if I have a library table with many books in a related "book" table and I delete a given library from my library table its' dependent book records will also be deleted.
Upvotes: 1
Reputation: 837996
A foreign key describes a relationship between two tables. It has many benefits:
If you are using MyISAM then foreign keys are not supported.
Upvotes: 12
Reputation: 190907
A foreign key is a reference to a primary key in another table or the table itself. It is used for what is called referential integrity. Basically in your table provided, for a Record to be inserted into Favorites
- you would have to supply a valid user_id
from the Users
table, and a valid movie_id
from the Movies
table. With Foreign keys enforces, I could not delete a record from Users
or Movies
. If I didn't have foreign keys, I could delete those records. Then if I did a SELECT ... JOIN
on Favorites
it would break.
See Wikipedia.
Upvotes: 15