我使用的是MySQL数据库。

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


当前回答

主键和唯一键的区别

主键和唯一键用于唯一地定义表中的一行。 主键创建列的聚集索引,而唯一键创建列的非聚集索引。

主键不允许空值,但唯一键允许一个空值。

其他回答

Primary Key Unique Key
A primary key can't accept NULL values Unique key can accept NULL values, so problematic in the context of being unique
A primary key cannot contain duplicate values A unique key also cannot contain duplicate values
We can have only one primary key in a table We can have more than one unique key in a table
We can make a primary key from one or more table fields We can also make a unique key from one or more table fields
By default, a primary key creates a clustered index By default, a unique key creates a non-clustered unique index
It is used to identify each record in the table It prevents storing duplicate entries in a column

主键必须唯一。

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

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

简单的主键是唯一的,不能为空,唯一的可以为空,也可以不是唯一的。

主键和唯一键的区别

主键和唯一键用于唯一地定义表中的一行。 主键创建列的聚集索引,而唯一键创建列的非聚集索引。

主键不允许空值,但唯一键允许一个空值。

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

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

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

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

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