1. 主键与聚集索引 首先澄清一个概念,主键并不等于聚集索引。(这不是废话么,如果是同一个东西,微软也不会叫两个不同的名字了) 一个表只能有一个聚集索引,数据在物理上是按照聚集索引的顺序来存放的。 主键分为聚集的主键和非聚集的主键。默认是聚集的主
1. 主键与聚集索引
首先澄清一个概念,主键并不等于聚集索引。(这不是废话么,如果是同一个东西,微软也不会叫两个不同的名字了)
一个表只能有一个聚集索引,数据在物理上是按照聚集索引的顺序来存放的。
主键分为聚集的主键和非聚集的主键。默认是聚集的主键。下面代码是sqlserver自动生成的create table 代码,注意设定主键那句话中的'
clustered',即表示聚集的主键。
/****** object: table [dbo].[user] script date: 03/28/2014 15:14:53 ******/
set ansi_nulls on
go
set quoted_identifier on
go
create table [dbo].[user](
[id] [int] identity(1,1) not null,
[schoolid] [nvarchar](50) not null,
[studentid] [nvarchar](50) not null,
[timeline] [nvarchar](50) not null,
[name] [nvarchar](50) null,
[phone] [nvarchar](50) null,
[gender] [nvarchar](50) null,
[age] [smallint] null,
[idcard] [nvarchar](50) null,
[nation] [nvarchar](50) null,
[party] [nvarchar](50) null,
[birthday] [nvarchar](50) null,
[married] [nvarchar](50) null,
[school] [nvarchar](50) null,
[degree] [nvarchar](50) null,
[province] [nvarchar](50) null,
[city] [nvarchar](50) null,
[area] [nvarchar](50) null,
[address] [nvarchar](50) null,
[college] [nvarchar](50) null,
[major] [nvarchar](50) null,
[class] [nvarchar](50) null,
[extra] [text] null,
primary key clustered
(
[id] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary] textimage_on [primary]
go
2. 多列索引和多个单列索引
考虑两种不同的建立索引方式:
case 1:对c1,c2,c3三列按此顺序添加一个多列索引;
case 2: 对c1,c2,c3分别建立三个单列索引;
问题1:按c1搜索时,哪种索引效率快?
答:case2
问题2:按c2搜索时,哪种索引效率快?
答:case2,并且,case1的索引无效
问题3:按c1,c2搜索时哪种效率快?
答:不知道
问题四:按c1,c2,c3搜索哪种效率快?
答:case1
问题五:按c2,c3,c1搜索时哪种效率快?
答:case2,因为没有按多列索引的顺序搜索,,case1的索引没有使用到。
3. 覆盖查询
所谓覆盖查询简单的说就是所有查询列被所使用的索引覆盖的查询。
4. 单个表中索引太多的负面影响
当一个表存在多个(单列)索引,将造成delete ,update ,insert操作需要花费大量的时间删除索引和重建索引。
通过把多个(单列)索引合并成一个(多列)索引后,测试得出delete ,update ,insert操作时需要花费的时间大大缩短。但是这样可能会对之前单列索引字段的查询性能有影响。个中好处,权衡取舍。