我使用的是MySQL数据库。
在哪些情况下我应该创建唯一键或主键?
我使用的是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,比如餐馆里的小吃 可能你在餐馆里不带零食
其他回答
主键和唯一键的区别
主键和唯一键用于唯一地定义表中的一行。 主键创建列的聚集索引,而唯一键创建列的非聚集索引。
主键不允许空值,但唯一键允许一个空值。
主键具有标识数据库行的语义。因此,一个给定的表只能有一个主键,而可以有许多唯一键。
同样的原因,主键不能为NULL(至少在Oracle中,其他数据库就不确定了)
因为它标识了行,所以它永远不应该更改。改变主键一定会造成严重的痛苦,甚至可能是永恒的诅咒。
因此,在大多数情况下,你需要一些人为的id作为主键,它只用于标识表中的单行。
另一方面,唯一键可以随心所欲地更改。
唯一键(英国):它是一列或一组列,可以识别一行中的唯一性。
主键(PK):它也是一列或一组列,可以识别一行中的唯一性。
因此,主键只是唯一键的另一个名称,但SQL Server中的默认实现对主键和唯一键是不同的。
默认情况下:
PK创建聚集索引,UK创建非聚集索引。 PK不为空,但是UK允许为空(注意:默认情况下) 一张桌子上只能有一个且只有一个PK,但可以有多个UK 您可以根据需要重写默认实现。
这取决于你在决定是创造UK还是PK时的目标是什么 “如果有三个人的团队,那么他们都是同行,但其中会有一个人是一对同行:PK和UK有类似的关系。”我建议阅读这篇文章:作者给出的例子可能看起来不太合适,但试着得到一个整体的想法。
http://tsqltips.blogspot.com/2012/06/difference-between-unique-key-and.html
主键是唯一的键。
每个表最多只能有一个主键,但可以有多个唯一键。主键用于唯一地标识表行。主键不能为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.