SQL Server(MySql)中的联合主键(联合索引) 索引分析

最近有人问到这个问题,以前也一直没有深究联合索引具体使用逻辑,查阅多篇文章,并通过测试,得出一些结论数据库

测试环境:SQL Server 2008 R2测试

测试结果与MySql联合索引查询机制相似,能够认为MySql是同样的原理spa

====================================================code

联合索引概念:当系统中某几个字段常常要作查询,而且数据量较大,达到百万级别,可多个字段建成索引blog

使用规则:索引

1.最 原则,根据索引字段,由左往右依次and(where字段很重要,从左往右字符串

2.Or 不会使用联合索引get

3.where语句中查询字段包含所有索引字段字段顺序无关,可随意前后it

4.数据量较少时,通常不会使用索引,数据库自己机制会自动判断是否使用索引table

=====================================================

测试脚本(部分借鉴其余做者的脚本):

/*建立测试数据表*/
create table MyTestTable
(
id varchar(10)not null,
parent varchar(40) not null,
addtime datetime default(getdate()),
intcolumn int default(10),
bitcolumn bit default(1)
)
go
/*添加万条随机字符串测试数据耗时分钟*/
declare @count int=3557643
declare @i int =0
declare @id varchar(10),@parent varchar(40)
while(@i<@count)
begin
select @id=left(newid(),10)
if(@i % 20=0)
begin
select @parent=left(newid(),40)
end
insert MyTestTable(id,parent) values(@id,@parent)
select @i=@i+1
end
go
/×未建索引查询测试×/
declare
@beginTime datetime =getdate() declare @elapsedSecond int =0 select * from MyTestTable where parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4' and id='FD3687F4-1' select @elapsedSecond=DATEDIFF(MICROSECOND,@beginTime,GETDATE()) print '未创建索引时查找数据消耗微秒数' print @elapsedSecond select @beginTime=GETDATE() select * from MyTestTable where parent='F535C18F-BD48-4D45-88DF-9653BB9B422D' select @elapsedSecond=DATEDIFF(MICROSECOND,@beginTime,GETDATE()) print '未创建索引时查找第二列数据消耗微秒数' print @elapsedSecond
/*创建索引*/
alter table MyTestTable add constraint PK_id_parent primary key(id asc,parent asc)

/*创建索引后的查询*/
declare @beginTime datetime =getdate()
declare @elapsedSecond int =0
select * from MyTestTable where parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4' and id='FD3687F4-1'
select @elapsedSecond=DATEDIFF(MICROSECOND,@beginTime,GETDATE())
print '创建索引时查找数据消耗微秒数'
print @elapsedSecond
 
select @beginTime=GETDATE()
select * from MyTestTable where parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4'
select @elapsedSecond=DATEDIFF(MICROSECOND,@beginTime,GETDATE())
print '创建索引后查找第二列数据消耗微秒数'
print @elapsedSecond
/*索引使用测试结论*/
select * from MyTestTable where   id='FD3687F4-1' --用索引
select * from MyTestTable where  id='FD3687F4-1' and parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4' and intcolumn>0  --用索引
select * from MyTestTable where  id='FD3687F4-1' and intcolumn>0  and parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4'    --用索引
select * from MyTestTable where  id='FD3687F4-1' and intcolumn>0 --用索引
select * from MyTestTable where parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4' and id='FD3687F4-1'   --用索引

select * from MyTestTable where   parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4' and intcolumn>0   --不用索引
select * from MyTestTable where parent='F92D6A9D-4E9E-4980-8B46-8AD938CEDCB4' or id='FD3687F4-1'   --不用索引

若有问题欢迎留言交流!

相关文章
相关标签/搜索