• 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

  • 相关阅读:
    如何使用Dev C++调试(debug)c程序
    C内存对齐详解
    epics commands
    #include <errno.h>
    linux中tail命令
    source env then start eclipse
    c++ constructor with para
    如何访问虚拟机中的架设的Web服务器(解决方法)
    dcss_gui_handler
    atlsoap.h”: No such file or directory
  • 原文地址:https://www.cnblogs.com/760044827qq/p/4389223.html
Copyright © 2020-2023  润新知