我什么时候应该使用主键或索引? [英] When should I use primary key or index?

查看:559
本文介绍了我什么时候应该使用主键或索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该何时使用主键或索引?

When should I use a primary key or an index?

他们有什么不同,哪个最好?

What are their differences and which is the best?

推荐答案

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

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中的相等或大于/小于的比较要快得多。但请注意,每个索引都会降低更新/插入/删除性能,因此您应该只将它们放在实际需要的位置。

这篇关于我什么时候应该使用主键或索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆