zoukankan      html  css  js  c++  java
  • SQL 索引的用法(转)

    下面测试的数据是3852916条记录。
    测试环境是 os:windows xp sp2, 内存:1G,cpu:双核 2.66 GHZ。

    (1)ItemTransaction 表什么都没有,没有主键,没有外键,没有索引。 
    declare @d datetime
    set @d=getdate()

    select * from Itemtransaction
    where logdate>'2008-9-1' and logdate<'2009-7-1'

    select 'yongshi:'=datediff(ss,@d,getdate())

    用时间:278秒(即:4分39秒)

    (2)ItemTransaction 表中只在logdate上创建非聚集索引。

    declare @d datetime
    set @d=getdate()

    select * from Itemtransaction
    where logdate>'2008-9-1' and logdate<'2009-7-1'

    select 'yongshi:'=datediff(ss,@d,getdate())

    用时间:182秒(即:3分04秒)

    快了1分30秒,速度没有想象中的那样快,看来在longdate上建立聚集索引不行。不符合聚集索引的要求“既不能绝大多数都相同,又不能只有极少数相同”。分析一下这张表
    数据总数 3852916 ,但是logdate不相同的数据只有360条一年(因为logdate是时间,一天只有一个时间,
    一年只有360条。)相比300万的数据来说,只能是极少。一般1:200比较合适。


    ----------------------------------------------------
    (3)ItemTransaction 表中创建一个logdate聚集索引。

      declare @d datetime
    set @d=getdate()

    select * from Itemtransaction
    where  logdate='2009-4-1' and employeeno=804562132
    select 'yongshi:'=datediff(ss,@d,getdate())


    用时间:45秒

    (4)ItemTransaction 表中创建一个logdate,employeeno 的复合聚集索引。

      declare @d datetime
    set @d=getdate()

    select * from Itemtransaction
    where  logdate='2009-4-1' and employeeno=804562132
    select 'yongshi:'=datediff(ss,@d,getdate())


    用时间:40秒


    (5)ItemTransaction 表中创建一个logdate,employeeno 的复合聚集索引。

      declare @d datetime
    set @d=getdate()

    select * from Itemtransaction
    where   employeeno=804562132 
    select 'yongshi:'=datediff(ss,@d,getdate())


    用时间:55秒


    通过这三个语句的比较:(3)中只有一个logdate索引,(4)中是logdate和employeeno的符合索引
    where 条件都是一样的。查询出来的速度差不多。 但是从(5)中看查询数据慢了。跟(4)比较,只是where 中的条件的先后顺序有所变化,正式这个顺序的变化,引起的。这是因为复合聚集索引中logdate,和employeeno的排列顺序不同。我的排列顺序是logdate 是第一位,employeeno是第二位。当你用的不是符合索引的起始列作为查询条件的话,这个索引的速度会慢下来。
    甚至不起作用。


    -----------------------------
    所谓索引就是在其他地方保存一些键值对,键即所为的索引列,值即地址指针。并且是按照顺序排列的。

    (5)employeeTransaction 表中union 和or 的比较

       用or:
      select * from employeetransaction
      where logdate>'2009-1-1' or Prodgroup='D1G'

      用时间:03分:05秒

      用union.
       select * from employeetransaction
       where logdate>'2009-1-1'
       union
       select * from employeetransaction
        where Prodgroup='D1G'

      用时间:03分:41秒

    在logdate,prodgroup上没有建立索引.看来这两者的速度相差不多.


    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wobuwei/archive/2009/08/26/4486105.aspx

  • 相关阅读:
    SPSS-Friedman 秩和检验-非参数检验-K个相关样本检验 案例解析
    SPSS-多重响应-频率和交叉表案例分析(问卷调查分析)
    SPSS--回归-多元线性回归模型案例解析
    深入理解RunLoop
    杂七杂八集合
    单元测试
    笔记
    http断点续传
    iOS性能优化
    群聊协议
  • 原文地址:https://www.cnblogs.com/760044827qq/p/4389223.html
Copyright © 2011-2022 走看看