且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该使用主键或索引?

更新时间:2022-12-08 12:23:17

基本上,主键是(在实现级别)一种特殊的索引。具体来说:

Basically, a primary key is (at the implementation level) a special kind of index. Specifically:


  • 一个表只能有一个主键,除了极少数例外,每个表都应该有一个。

  • 主键是隐式 UNIQUE - 你不能有多个具有相同主键的行,因为它的目的是唯一地标识行。

  • 主键永远不能是 NULL ,所以它所包含的行必须是NOT NULL

  • A table can have only one primary key, and with very few exceptions, every table should have one.
  • A primary key is implicitly UNIQUE - you cannot have more than one row with the same primary key, since its purpose is to uniquely identify rows.
  • A primary key can never be NULL, so the row(s) it consists of must be NOT NULL

一个表可以有多个索引,索引不一定是 UNIQUE 。索引存在有两个原因:

A table can have multiple indexes, and indexes are not necessarily UNIQUE. Indexes exist for two reasons:


  • 强制执行单一约束(当您声明列UNIQUE时可以隐式创建这些约束)

  • 提高性能。在具有索引的列上,WHERE子句以及JOIN中的相等或大于/小于的比较要快得多。但请注意,每个索引都会降低更新/插入/删除性能,因此您应该只将它们放在实际需要的位置。