为什么使用多列作为主键(复合主键) [英] Why use multiple columns as primary keys (composite primary key)
问题描述
此示例取自 来自 w3schools.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
我的理解是这两列(P_Id
和 LastName
)一起代表表 Persons
的主键.这是正确的吗?
My understanding is that both columns together (P_Id
and LastName
) represent a primary key for the table Persons
. Is this correct?
- 为什么有人要使用多列而不是单列作为主键?
- 可以将多少列一起用作给定表中的主键?
推荐答案
你的理解是正确的.
在许多情况下,您会这样做.一个例子是像OrderHeader
和OrderDetail
这样的关系.OrderHeader
中的 PK 可能是 OrderNumber
.OrderDetail
中的 PK 可能是 OrderNumber
AND LineNumber
.如果是这两者中的任何一个,它就不是唯一的,但两者的组合保证唯一.
You would do this in many cases. One example is in a relationship like OrderHeader
and OrderDetail
. The PK in OrderHeader
might be OrderNumber
. The PK in OrderDetail
might be OrderNumber
AND LineNumber
. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.
另一种方法是使用生成的(非智能)主键,例如在这种情况下 OrderDetailId
.但那样你就不会总是那么容易地看到这种关系.有些人更喜欢一种方式;有些人更喜欢另一种方式.
The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId
. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.
这篇关于为什么使用多列作为主键(复合主键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!