我使用的是MySQL数据库。

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


当前回答

主键必须唯一。

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

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

其他回答

主键是唯一的键。

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

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

Think the table name is employe. Primary key Primary key can not accept null values. primary key enforces uniqueness of a column. We can have only one Primary key in a table. Unique key Unique key can accept null values. unique key also enforces uniqueness of a column.you can think if unique key contains null values then why it can be unique ? yes, though it can accept null values it enforces uniqueness of a column. just have a look on the picture.here Emp_ID is primary and Citizen ID is unique. Hope you understand. We can use multiple unique key in a table.

如果你的数据库设计不需要外键,那么你可以使用唯一键(但记住唯一键允许单个空值)。

如果数据库需要外键那么你别无选择只能用主键。

要查看唯一键和主键之间的区别,请访问这里

主键的主要特征是:

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

唯一键的主要特征是:

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

它也可以包含空值。

一个表中有多个唯一键。