我使用的是MySQL数据库。

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


当前回答

主键必须唯一。

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

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

其他回答

Unique key :- It should be used when you have to give unique value.In the case of unique key it means null values are also allowed.Unique keys are those keys which are unique and non similar in that column like for example your pet name.it can be nothing like null and if you are asking in context of database then it must be noted that every null is different from another null in the database.EXCEPT-SQL Server where null=null is true


主键:— 它应该在必须唯一标识一行时使用。Primary是一个键,它对数据库约束中的每一行都是唯一的,它不允许它为空。你可能看到数据库中有一个列是自动递增的它是表的主键。另外,它可以在另一个表中用作外键。例如订单表中的orderId,账单表中的billId。 现在回到什么情况下使用它:-

1)主键在哪个列可以 在表中不是空,并且在另一个表中用作外键 用于创建关系的表

2)唯一键在表中所在 不影响在表中或在整个数据库中 对于特定列为Null,比如餐馆里的小吃 可能你在餐馆里不带零食

主键和唯一键的区别

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

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

主键:

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

独特的关键:

一个表中可以有多个唯一键吗 唯一键可以有NULL值 它可以是一个候选密钥 唯一键可以为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