MySql - 默认情况下主键是唯一的吗?

时间:2022-09-16 09:55:58

If I define a column as a primary key in MySql, is it also unique key by default or do I need to also define it as unique key (in case I want it to be unique)?

如果我在MySql中将列定义为主键,默认情况下它是否也是唯一键还是我还需要将其定义为唯一键(如果我希望它是唯一的)?

I saw this question What is the difference b/w Primary Key and Unique Key that explain the difference between the two but doesn't exactly answer my question. Does PK is UK by default or I need to explicitly define it.

我看到了这个问题b / w主键和唯一键有什么区别,它解释了两者之间的区别,但没有完全回答我的问题。默认情况下PK是UK还是我需要明确定义它。

2 个解决方案

#1


21  

Primary key is always unique in every SQL. You dont have to explicitly define it as UNIQUE.

主键在每个SQL中始终是唯一的。你不必明确地将它定义为UNIQUE。

On a side note: You can only have onePrimary key in a table and it never allows null values. Also you can have only one primary key constraint in the table(as the point of creating a primary key is to uniquely identify the row in your table) but you can more than one unique key constraint in your table.

注意:在表中只能有一个主键,它永远不会允许空值。此外,表中只能有一个主键约束(因为创建主键的目的是唯一标识表中的行),但表中可以有多个唯一键约束。

Example:

例:

An employee details table having EmpID as Primary key and EmpPhoneNo as unique key.

员工详细信息表,其中EmpID为主键,EmpPhoneNo为唯一键。

#2


3  

Primary key is always unique by definition. Not only in MySQL. So you don't need any additional unique key.

根据定义,主键始终是唯一的。不仅在MySQL中。所以你不需要任何额外的唯一密钥。

#1


21  

Primary key is always unique in every SQL. You dont have to explicitly define it as UNIQUE.

主键在每个SQL中始终是唯一的。你不必明确地将它定义为UNIQUE。

On a side note: You can only have onePrimary key in a table and it never allows null values. Also you can have only one primary key constraint in the table(as the point of creating a primary key is to uniquely identify the row in your table) but you can more than one unique key constraint in your table.

注意:在表中只能有一个主键,它永远不会允许空值。此外,表中只能有一个主键约束(因为创建主键的目的是唯一标识表中的行),但表中可以有多个唯一键约束。

Example:

例:

An employee details table having EmpID as Primary key and EmpPhoneNo as unique key.

员工详细信息表,其中EmpID为主键,EmpPhoneNo为唯一键。

#2


3  

Primary key is always unique by definition. Not only in MySQL. So you don't need any additional unique key.

根据定义,主键始终是唯一的。不仅在MySQL中。所以你不需要任何额外的唯一密钥。