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

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

问题描述

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

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天全站免登陆