我使用的是MySQL数据库。

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


当前回答

主键:

一个表中只能有一个主键约束 在一些DBMS中,它不能为NULL,例如MySQL添加了NOT NULL 主键是记录的唯一键标识符

独特的关键:

一个表中可以有多个唯一键吗 唯一键可以有NULL值 它可以是一个候选密钥 唯一键可以为NULL;多行可以有NULL值,因此可能不被认为是“唯一的”

其他回答

主键和唯一键的区别

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

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

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

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

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

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.

主键:

一个表中只能有一个主键约束 在一些DBMS中,它不能为NULL,例如MySQL添加了NOT NULL 主键是记录的唯一键标识符

独特的关键:

一个表中可以有多个唯一键吗 唯一键可以有NULL值 它可以是一个候选密钥 唯一键可以为NULL;多行可以有NULL值,因此可能不被认为是“唯一的”

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

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

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.

好了!