1
create table categories(a integer unsigned NOT NULL,b integer unsigned NOT NULL,primary key(a,b));

create table categories(a integer unsigned NOT NULL,b integer unsigned NOT NULL,unique (a,b));

有什么功能上的区别吗?

4

4 回答 4

1

Yes, you can have only one primary key, but you can have as many unique indexes as you like.

于 2010-02-21T11:29:30.487 回答
1

有什么功能上的区别吗?

primary key通常,a和约束之间的区别在于unique您可以在可为空的列上创建后者。也就是说,您可以在未显式声明的列上创建主键NOT NULL,但由于添加主键,这些将自动变为不可为空。此外,您只能有一个主键,但可以有许多唯一约束。

现在,在您的示例代码中,无论如何,两列都是如此,因此在功能上,和约束NOT NULL之间没有任何区别。但是这种明显没有差异仅适用于表的逻辑关系属性。存储引擎级别可能仍然存在差异。primary keyunique

例如,innodb 存储引擎使用聚集索引:表数据存储在为主键创建的索引的叶子节点中。因此,如果您有一个没有主键的 innodb 表,innodb 仍会在幕后创建一个,并且您的唯一索引将指向主键中的实体。如果您没有明确定义主键,其他引擎(如 NDB 集群引擎)也会自动创建主键,在这种情况下,任何二级索引(如唯一索引)都将指向主键中的整体。在这两种情况下,这些二级索引通常会比它们最初被定义为主键时要慢。

在 MySQL 中,还有一个与主键和唯一约束相关的区别。如果要创建auto_increment列,则该列必须是主键的一部分(通常,主键仅包含auto_increment列)

除了这些技术差异之外,还有一个约定问题需要考虑。始终定义主键被认为是一种很好的做法 - 基本上你是在说,“这是识别此表中的行的规范方法”。如果你忽略它,它会产生混乱,因为它看起来像你忘记定义一个。

于 2010-02-21T11:48:18.637 回答
0

Have a look at The difference between a unique index and primary key in MySQL

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL

于 2010-02-21T11:30:34.933 回答
0

Primary keys are like unique indexes except:

  • Cannot contain NULLable columns
  • Some storage engines treat them differently - InnoDB, for example, clusters the primary key, which can sometimes be a Good Thing, occasionally be a Bad Thing, but mostly not matter.

As they can't have NULLs, a primary key MUST uniquely identify a row.

于 2010-02-21T11:44:32.003 回答