什么是MySQL外键? [英] What are MySQL foreign keys?

查看:97
本文介绍了什么是MySQL外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有关堆栈溢出的答案中,我看到了以下代码:

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.

  • 这是什么?
  • 人们为什么使用它?
  • 除了语义之外,它还能提供任何好处吗?

推荐答案

外键是对另一个表或表本身中主键的引用.它用于所谓的 参照完整性 .基本上在提供的表中,要将记录插入到Favorites中,您将必须提供Users表中的有效user_idMovies表中的有效movie_id.使用外键强制,我无法从UsersMovies删除记录.如果没有外键,则可以删除这些记录.然后,如果我在Favorites上执行了SELECT ... JOIN,它将损坏.

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.

请参见维基百科.

这篇关于什么是MySQL外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆