究竟什么是外键? [英] What exactly is a foreign key?
问题描述
好的.所以我知道数据库中的主键是什么.如果您在数据库中有一个表,则主键是表中每一行唯一的单个值.例如:
Ok. So I know what a primary key in DB is. If you have a table in a database, a primary key is a single value that is unique to each row in your table. For example:
id | name | whatever
-------------------------
1 Alice ....
2 Bob ....
45 Eve ....
988 .... ....
所以我需要一个好的、简单的例子来解释外键到底是什么.因为我就是不明白:)
So I need a good, simple example to explain what exactly a foreign key is. Because I just don't get it :)
好的,这很简单,我想我把问题复杂化了.
OK it's pretty easy, I guess I was over-complicating the problem.
最后一个问题,外键的唯一限制是它们是我所指的表中的有效主键值吗?
So one final question, the only restriction on foreign keys is that it they are a valid primary key value in the table I am referring to?
推荐答案
外键是指向另一个表的主键的字段.
A foreign key is a field that points to a primary key of another table.
例子:
Table Name - Users
UserID UserName UserRoleID
1 JohnD 1
2 CourtneyC 1
3 Benjamin 2
Table Name - UserRoles
UserRoleID Desc
1 Admin
2 Moderator
您可以看到 Users.UserRoleID 是一个外键,它指向主键 UserRoles.UserRoleID
You can see that Users.UserRoleID is a foreign key which points to the primary key UserRoles.UserRoleID
外键的使用使得在其他表上建立关系变得简单,允许您以一种很好的方式将多个表的数据链接在一起:
The use of foreign keys makes setting up relationships on other tables simple, allowing you to link together the data of multiple tables in a nice way:
例子:
SELECT
a.UserID,
a.UserName,
b.Desc as [UserRole]
FROM
Users a INNER JOIN
UserRoles b ON a.UserRoleID = b.UserRoleID
然后输出将是:
UserID UserName User Role
1 JohnD Admin
2 CourneyC Admin
3 Benjamin Moderator
这篇关于究竟什么是外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!