问题描述
我试图在谷歌上找到它,但那里给出的答案并不令人满意.任何人都可以解释明显的区别.
I tried to find it out in google but not satisfactory answer is given out there. Can anybody explain the solid difference.
实际上如果使用主键来唯一选择数据,那么唯一键有什么必要呢?
actually if Primary key is used to select data uniquely then what is the need of Unique key?
什么时候应该使用主键,什么时候应该使用唯一键?
When should I use a Primary key and when to use a Unique key?
推荐答案
Primary Key 和 Unique Key 用于不同的事情 - 了解它们的用途将有助于您决定何时使用它们.
Primary Key and Unique Key are used for different things - understanding what they are for will help you decide when to use them.
主键用于标识表中的一行数据.每当您需要引用特定行时,就会使用它,例如.在其他表中或通过应用程序代码等.为了标识一行,PK 的值必须是唯一的.此外,它们不能为 null,因为大多数 DBMS 将 null 视为不等于 null(因为 null 通常意味着未知").一张桌子只能有一个PK.数据库中的所有表都应该有一个 PK(尽管大多数 DBMS 不强制执行),并且 PK 可以跨越多个列.
The primary key is used to identify a row of data in a table. It is used whenever you need to refer to a particular row, eg. in other tables or by application code etc. In order to identify a row, the values of a PK must be unique. Furthermore, they can't be null, because most DBMS treat null as not equal to null (since null typically means "unknown"). A table can only have one PK. All tables in your database should have a PK (although this is not enforced by most DBMS), and PK can span multiple columns.
唯一键约束用于确保数据不会在数据库中的两行中重复.对于唯一键约束的值,允许数据库中的一行为空.虽然表应该有一个 PK,但它不需要任何额外的唯一键.但是,如果满足您的需要,表可以有多个唯一键.与 PK 一样,唯一键可以跨越多列.
Unique key constraints are used to ensure that data is not duplicated in two rows in the database. One row in the database is allowed to have null for the value of the unique key constraint. Although a table should have a PK, it need not have any additional unique keys. However, tables can have more than one unique key if that meets your needs. Like PKs, unique keys can span multiple columns.
还值得知道的是,默认情况下,许多 DBMS 索引和使用 PK 对磁盘上的表进行物理排序.这意味着通过 PK 查找值比在一行中使用其他值更快.但是,通常情况下,您可以根据需要覆盖此行为.
It is also worth knowing that, by default, many DBMS index and physically order tables on disk using the PK. This means that looking up values by their PK is faster than using other values in a row. Typically, however, you can override this behaviour if required.
这篇关于黑白主键和唯一键有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!