我使用的是MySQL数据库。

在哪些情况下我应该创建唯一键或主键?


当前回答

我知道这个问题已经有好几年了,但我想提供一个答案,解释为什么而不是如何

主键的作用:在数据库中唯一地标识一行=>一行表示表建模的实体类型的单个实例。主键强制实体的完整性,即实体完整性。主键将是一个聚集索引,即它定义了数据在表中物理存储的顺序。

Purpose of Unique Key: Ok, with the Primary Key we have a way to uniquely identify a row. But I have a business need such that, another column/a set of columns should have unique values. Well, technically, given that this column(s) is unique, it can be a candidate to enforce entity integrity. But for all we know, this column can contain data originating from an external organization that I may have a doubt about being unique. I may not trust it to provide entity integrity. I just make it a unique key to fulfill my business requirement.

好了!

其他回答

我知道这个问题已经有好几年了,但我想提供一个答案,解释为什么而不是如何

主键的作用:在数据库中唯一地标识一行=>一行表示表建模的实体类型的单个实例。主键强制实体的完整性,即实体完整性。主键将是一个聚集索引,即它定义了数据在表中物理存储的顺序。

Purpose of Unique Key: Ok, with the Primary Key we have a way to uniquely identify a row. But I have a business need such that, another column/a set of columns should have unique values. Well, technically, given that this column(s) is unique, it can be a candidate to enforce entity integrity. But for all we know, this column can contain data originating from an external organization that I may have a doubt about being unique. I may not trust it to provide entity integrity. I just make it a unique key to fulfill my business requirement.

好了!

主键的主要特征是:

它必须为每一行数据包含一个惟一的值。 不能包含空值。 一个表中只能有一个主键。

唯一键的主要特征是:

它还可以为每一行数据包含一个惟一的值。

它也可以包含空值。

一个表中有多个唯一键。

主键必须唯一。

唯一键不一定是主键-请参阅候选键。

也就是说,一个表上可能有多个列的组合可以唯一地标识一行——其中只有一个可以被选择为主键。其他键虽然是唯一的,但都是候选键。

主键具有标识数据库行的语义。因此,一个给定的表只能有一个主键,而可以有许多唯一键。

同样的原因,主键不能为NULL(至少在Oracle中,其他数据库就不确定了)

因为它标识了行,所以它永远不应该更改。改变主键一定会造成严重的痛苦,甚至可能是永恒的诅咒。

因此,在大多数情况下,你需要一些人为的id作为主键,它只用于标识表中的单行。

另一方面,唯一键可以随心所欲地更改。

主键是唯一的键。

每个表最多只能有一个主键,但可以有多个唯一键。主键用于唯一地标识表行。主键不能为NULL,因为NULL不是一个值。