我使用的是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

主键和唯一键的区别

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

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

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

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.

对于一个组织或企业来说,有许多物理实体(如人员、资源、机器等)和虚拟实体(它们的任务、事务、活动)。 通常,业务需要记录和处理这些业务实体的信息。 这些业务实体在整个业务域中由一个Key标识。

根据RDBMS的预期,密钥(又名候选密钥)是唯一标识一个实体的一个值或一组值。

对于一个DB-Table,有很多存在的键,并且可能符合主键的条件。 因此,所有键、主键、唯一键等统称为候选键。 但是,DBA从候选密钥中选择一个用于搜索记录的密钥称为主密钥。

主键和唯一键的区别

1. 行为:主键用于标识表中的一行(记录),而唯一键用于防止列中的重复值(空项除外)。

2. 索引:默认情况下,sql引擎在主键上创建聚集索引(如果不存在),在唯一键上创建非聚集索引。

3.可空性:主键不包括空值,而唯一键可以。

4. 存在:一个表最多只能有一个主键,但可以有多个唯一键。

5. 可修改性:您不能更改或删除主值,但唯一键值可以。

更多信息和示例:

http://dotnetauthorities.blogspot.in/2013/11/Microsoft-SQL-Server-Training-Online-Learning-Classes-Integrity-Constraints-PrimaryKey-Unique-Key_27.html