create index ind_A on XX表(A,C)
create index ind_B on XX表(A)

解决方案 »

  1.   

    一、不合理的索引设计
    ----例:表record有620000行,试看在不同的索引下,下面几个 SQL的运行情况:
    ---- 1.在date上建有一非个群集索引
    select count(*) from record where date >
    '19991201' and date < '19991214'and amount >
    2000 (25秒)
    select date,sum(amount) from record group by date
    (55秒)
    select count(*) from record where date >
    '19990901' and place in ('BJ','SH') (27秒)
    ---- 分析:
    ----date上有大量的重复值,在非群集索引下,数据在物理上随机存放在数据页上,在
    范围查找时,必须执行一次表扫描才能找到这一范围内的全部行。
    ---- 2.在date上的一个群集索引
    select count(*) from record where date >
    '19991201' and date < '19991214' and amount >
    2000 (14秒)
    select date,sum(amount) from record group by date
    (28秒)
    select count(*) from record where date >
    '19990901' and place in ('BJ','SH')(14秒)
    ---- 分析:
    ---- 在群集索引下,数据在物理上按顺序在数据页上,重复值也排列在一起,因而在范
    围查找时,可以先找到这个范围的起末点,且只在这个范围内扫描数据页,避免了大范
    围扫描,提高了查询速度。
    ---- 3.在place,date,amount上的组合索引
    select count(*) from record where date >
    '19991201' and date < '19991214' and amount >
    2000 (26秒)
    select date,sum(amount) from record group by date
    (27秒)
    select count(*) from record where date >
    '19990901' and place in ('BJ, 'SH')(< 1秒)
    ---- 分析:
    ---- 这是一个不很合理的组合索引,因为它的前导列是place,第一和第二条SQL没有引
    用place,因此也没有利用上索引;第三个SQL使用了place,且引用的所有列都包含在组
    合索引中,形成了索引覆盖,所以它的速度是非常快的。
    ---- 4.在date,place,amount上的组合索引
    select count(*) from record where date >
    '19991201' and date < '19991214' and amount >
    2000(< 1秒)
    select date,sum(amount) from record group by date
    (11秒)
    select count(*) from record where date >
    '19990901' and place in ('BJ','SH')(< 1秒)
    ---- 分析:
    ---- 这是一个合理的组合索引。它将date作为前导列,使每个SQL都可以利用索引,并
    且在第一和第三个SQL中形成了索引覆盖,因而性能达到了最优。
    ---- 5.总结:
    ---- 缺省情况下建立的索引是非群集索引,但有时它并不是最佳的;合理的索引设计要
    建立在对各种查询的分析和预测上。一般来说:
    ---- ①.有大量重复值、且经常有范围查询
    (between, >,< ,>=,< =)和order by
    、group by发生的列,可考虑建立群集索引;
    ---- ②.经常同时存取多列,且每列都含有重复值可考虑建立组合索引;
    ---- ③.组合索引要尽量使关键查询形成索引覆盖,其前导列一定是使用最频繁的列。