为什么要使用多个列作为主键(复合主键) [英] Why use multiple columns as primary keys (composite primary key)

查看:440
本文介绍了为什么要使用多个列作为主键(复合主键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例来自从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屋!

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