What are MySQL foreign keys?

后端 未结 3 2018
时光取名叫无心
时光取名叫无心 2021-02-01 23:20

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         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 23:53

    A foreign key describes a relationship between two tables. It has many benefits:

    • You can enforce that if a value is in the one table then it must also exist in the other table. Any attempt to break this constraint will give an error.
    • It allows database administrators or programmers to more easily understand the relationship between the tables just by looking at the table definitions.
    • It allows tools to inspect the schema and draw diagrams showing the relations between the tables, or create classes where the children of an object are accessible from the parent via members.
    • In InnoDB adding a foreign key also automatically adds an index on that column so that the join can be made efficiently in either direction. (Source)

    If you are using MyISAM then foreign keys are not supported.

提交回复
热议问题