如何让你的SQL运行得更快(转贴) 
---- 人们在使用SQL时往往会陷入一个误区,即太关注于所得的结果是否正确,而忽略
了不同的实现方法之间可能存在的性能差异,这种性能差异在大型的或是复杂的数据库
环境中(如联机事务处理OLTP或决策支持系统DSS)中表现得尤为明显。笔者在工作实践
中发现,不良的SQL往往来自于不恰当的索引设计、不充份的连接条件和不可优化的whe
re子句。在对它们进行适当的优化后,其运行速度有了明显地提高!下面我将从这三个
方面分别进行总结:
---- 为了更直观地说明问题,所有实例中的SQL运行时间均经过测试,不超过1秒的均
表示为(< 1秒)。
---- 测试环境--
---- 主机:HP LH II
---- 主频:330MHZ
---- 内存:128兆
---- 操作系统:Operserver5.0.4
----数据库:Sybase11.0.3
一、不合理的索引设计
----例:表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发生的列,可考虑建立群集索引;
---- ②.经常同时存取多列,且每列都含有重复值可考虑建立组合索引;
---- ③.组合索引要尽量使关键查询形成索引覆盖,其前导列一定是使用最频繁的列。二、不充份的连接条件:
---- 例:表card有7896行,在card_no上有一个非聚集索引,表account有191122行,在
account_no上有一个非聚集索引,试看在不同的表连接条件下,两个SQL的执行情况:select sum(a.amount) from account a,
card b where a.card_no = b.card_no(20秒)
---- 将SQL改为:
select sum(a.amount) from account a,
card b where a.card_no = b.card_no and a.
account_no=b.account_no(< 1秒)
---- 分析:
---- 在第一个连接条件下,最佳查询方案是将account作外层表,card作内层表,利用
card上的索引,其I/O次数可由以下公式估算为:
---- 外层表account上的22541页+(外层表account的191122行*内层表card上对应外层
表第一行所要查找的3页)=595907次I/O
---- 在第二个连接条件下,最佳查询方案是将card作外层表,account作内层表,利用
account上的索引,其I/O次数可由以下公式估算为:
---- 外层表card上的1944页+(外层表card的7896行*内层表account上对应外层表每一
行所要查找的4页)= 33528次I/O
---- 可见,只有充份的连接条件,真正的最佳方案才会被执行。
---- 总结:
---- 1.多表操作在被实际执行前,查询优化器会根据连接条件,列出几组可能的连接方
案并从中找出系统开销最小的最佳方案。连接条件要充份考虑带有索引的表、行数多的
表;内外表的选择可由公式:外层表中的匹配行数*内层表中每一次查找的次数确定,乘
积最小为最佳方案。
---- 2.查看执行方案的方法-- 用set showplanon,打开showplan选项,就可以看到连
接顺序、使用何种索引的信息;想看更详细的信息,需用sa角色执行dbcc(3604,310,30
2)。
三、不可优化的where子句
---- 1.例:下列SQL条件语句中的列都建有恰当的索引,但执行速度却非常慢:
select * from record where
substring(card_no,1,4)='5378'(13秒)
select * from record where
amount/30< 1000(11秒)
select * from record where
convert(char(10),date,112)='19991201'(10秒)
---- 分析:
---- where子句中对列的任何操作结果都是在SQL运行时逐列计算得到的,因此它不得不
进行表搜索,而没有使用该列上面的索引;如果这些结果在查询编译时就能得到,那么
就可以被SQL优化器优化,使用索引,避免表搜索,因此将SQL重写成下面这样:
select * from record where card_no like
'5378%'(< 1秒)
select * from record where amount
< 1000*30(< 1秒)
select * from record where date= '1999/12/01'
(< 1秒)
---- 你会发现SQL明显快起来!
---- 2.例:表stuff有200000行,id_no上有非群集索引,请看下面这个SQL:
select count(*) from stuff where id_no in('0','1')
(23秒)
---- 分析:
---- where条件中的'in'在逻辑上相当于'or',所以语法分析器会将in ('0','1')转化
为id_no ='0' or id_no='1'来执行。我们期望它会根据每个or子句分别查找,再将结果
相加,这样可以利用id_no上的索引;但实际上(根据showplan),它却采用了"OR策略"
,即先取出满足每个or子句的行,存入临时数据库的工作表中,再建立唯一索引以去掉
重复行,最后从这个临时表中计算结果。因此,实际过程没有利用id_no上索引,并且完
成时间还要受tempdb数据库性能的影响。
---- 实践证明,表的行数越多,工作表的性能就越差,当stuff有620000行时,执行时
间竟达到220秒!还不如将or子句分开:
select count(*) from stuff where id_no='0'
select count(*) from stuff where id_no='1'
---- 得到两个结果,再作一次加法合算。因为每句都使用了索引,执行时间只有3秒,
在620000行下,时间也只有4秒。或者,用更好的方法,写一个简单的存储过程:
create proc count_stuff as
declare @a int
declare @b int
declare @c int
declare @d char(10)
begin
select @a=count(*) from stuff where id_no='0'
select @b=count(*) from stuff where id_no='1'
end
select @c=@a+@b
select @d=convert(char(10),@c)
print @d
---- 直接算出结果,执行时间同上面一样快!
---- 总结:
---- 可见,所谓优化即where子句利用了索引,不可优化即发生了表扫描或额外开销。---- 1.任何对列的操作都将导致表扫描,它包括数据库函数、计算表达式等等,查询时
要尽可能将操作移至等号右边。
---- 2.in、or子句常会使用工作表,使索引失效;如果不产生大量重复值,可以考虑把
子句拆开;拆开的子句中应该包含索引。
---- 3.要善于使用存储过程,它使SQL变得更加灵活和高效。
---- 从以上这些例子可以看出,SQL优化的实质就是在结果正确的前提下,用优化器可
以识别的语句,充份利用索引,减少表扫描的I/O次数,尽量避免表搜索的发生。其实S
QL的性能优化是一个复杂的过程,上述这些只是在应用层次的一种体现,深入研究还会
涉及数据库层的资源配置、网络层的流量控制以及操作系统层的总体设计。

解决方案 »

  1.   


    文/交通银行长春分行电脑部 任亮 摘自计算机日报
    测试过程:环境:
    PIII900 128M
    win2000+sql server2000企业版
    table name :t_data
    CLUSTERED PRIMARY KEY  :id
    Rows:441000语句1:
    select * from t_data where 
    id in
    (select top 10 id  from t_data where id in
    (select top 60000 id  from t_data order by id asc)
    order by id desc)
    order by id asc时间:390ms语句2:
    select * from t_data where 
    id in
    (select top 10 id  from t_data where id in
    (select top 100000 id  from t_data order by id asc)
    order by id desc)
    order by id asc时间:4s语句3:
    select * from t_data where 
    id in
    (select top 10 id  from t_data where id in
    (select top 150000 id  from t_data order by id asc)
    order by id desc)
    order by id asc时间:5s语句4:
    select * from t_data where 
    id in
    (select top 10 id  from t_data where id in
    (select top 200000 id  from t_data order by id asc)
    order by id desc)
    order by id asc时间:6s语句5:
    select * from t_data where 
    id in
    (select top 10 id  from t_data where id in
    (select top 250000 id  from t_data order by id asc)
    order by id desc)
    order by id asc时间:过了15m没有出来,中断语句6:
    select * from t_data where 
    id in
    (select top 10 id  from t_data where id in
    (select top 300000 id  from t_data order by id asc)
    order by id desc)
    order by id asc时间:过了20m没有出来,中断语句7:
    select top 60000 id  into #a from t_data order by id asccreate index ind_a_base_id on #a(id)  select * from t_data where 
    id in (select top 10 id  from #a order by id desc)
    order by id asc时间:20s语句8:
    select top 100000 id  into #a from t_data order by id asccreate index ind_a_base_id on #a(id)  select * from t_data where 
    id in (select top 10 id  from #a order by id desc)
    order by id asc时间:21s语句9:
    select top 150000 id  into #a from t_data order by id asccreate index ind_a_base_id on #a(id)  select * from t_data where 
    id in (select top 10 id  from #a order by id desc)
    order by id asc时间:23s语句10:
    select top 200000 id  into #a from t_data order by id asccreate index ind_a_base_id on #a(id)  select * from t_data where 
    id in (select top 10 id  from #a order by id desc)
    order by id asc时间:24s语句11:
    select top 250000 id  into #a from t_data order by id asccreate index ind_a_base_id on #a(id)  select * from t_data where 
    id in (select top 10 id  from #a order by id desc)
    order by id asc时间:26s语句12:
    select top 300000 id  into #a from t_data order by id asccreate index ind_a_base_id on #a(id)  select * from t_data where 
    id in (select top 10 id  from #a order by id desc)
    order by id asc时间:28s语句13:
    select top 400000 id  into #a from t_data order by id asccreate index ind_a_base_id on #a(id)  select * from t_data where 
    id in (select top 10 id  from #a order by id desc)
    order by id asc时间:29s语句14:
    select * from t_data where 
    id in
    (select top 10 id  from t_data where id in
    (select top 250000 id  from t_data order by id asc)
    order by id desc)
    order by id asc时间:过了25m没有出来,还没有中断
      

  2.   

    //1.主要是看where后面条件,,,,,
    //2.看表的索引是否合理.许多情况下用复合索引来代替多个单一索引.
      

  3.   

    表设计得极其不合理..
    按你所说,有多少次不一样的比对就应该设计多少次.happydreamer(小黑-从头学起),你这贴子这几天快贴烂了
      

  4.   

    多谢各位关注,由于本人第一设计数据库开发,还是请各位多多详细指教!
    兼于各位的回贴,现说明如下:
    (1)一次比对首先产生要比对的三个数据a1,a2,a3和一系列序列号(不等),比如2000个,这每一个号与表中的序列号字段相对应,对于每一号都要通过查询表的方式定位到实际的存放数据项字段记录上;
    (2)比对时是a1,a2,a3与数据项字段中所有包含的数据项子项同样所包含在个数进行一一比对,如果在误差范围内相等的话,给对应的计数器加1;
    (3)把这2000个号搜索比对完毕才算这次比对结束.
    数据录入时也是根据不同的序列号追加到序列号对应数据项字段的后面,如果无此号,表才增加一个记录.
    请各位赐教,在这种情况下,应如何设计表才能提高速度??(数据项子项是7位整数,第一位是计数器编号,最后三位才是要比对的数据,现在录入时我是把它们转换为字符形,只有这样才能向varchar型数据项字段无限增加,比对时我用字符搜索的方式进行,我知道这样会占用好多时间,可我实在想不出好办法!!!除非在SQL Server中可变整形,可以在字段后自动增加数据??)
      

  5.   

    怎么没有人过问??急!急!急!
    在上述有300万条记录表中查找某标号(已设置为主键)用了0.5ms,还能不能再降低?在SQL Server 2000中怎样以最快的速度达到??--------参与有分!
      

  6.   

    明白你的意思了,
    是不是这样:   ID        ITEM(VCHAR)
                    1        123456712345671234567  
                    2        765432176543217654321
                    3        011223301122330112233
    Select ID[主键] from yourtable where id=yourvalue 这语句好象没办法优化了吧。还是从比数据项比对算法上动动脑筋,提高总体处理速度。
    比如:数据项子项是7位字符,每个子项目的后三位用来比较,那你可以做个循环取出每个子项的后三位用等于来比较,也可以取出每个子项用包含比较,哪个速度快就用哪个。
    你试试吧
      

  7.   

    谢谢!我也是从这方面考虑的,时间只是降低一点点,不过总算有收获,再请教一下,SQL SERVER中如何统计出表中的记录数?如何遍历整个表记录?有没有像ACCESS库那样的自动编号字段??(我是新手不要见笑)
      

  8.   

    自动编号有的
    首先字段必须是samllint,int,bigint等整形数据类型
    在企业管理器中进入表的设计状态,选中你要设置自动编号的字段,
    双击标识栏中的'否',变成'是'
    在表识栏下面那个文本框里写入你要自动编号的头一个编号(默认值是1,以1开始)
    再下面那个文本框中写入自动编号的增加量(默认值是1,自动加1)
      

  9.   

    谢谢!自动编号我已经实现了,不过如何根据自动编号统计出表中的记录数?如何遍历整个表记录?(用SQL语句实现)
      

  10.   

    1、优化where条件,并建立对应索引
    2、分割数据库。
      

  11.   

    得到记录数 select count(autoid) as recordcount from yourtable用SQL中遍历当然要用游标和循环了,如下:DECLARE @E_CODE CHAR(8),
            @E_ACCOUNT MONEY
       
    DECLARE CURSOR1 CURSOR 
    FOR SELECT 员工号,个人帐户金额 FROM 员工帐户表 WHERE 状态='T' //为记录集定义游标
    OPEN CURSOR1 
    FETCH NEXT FROM CURSOR1 INTO @E_CODE,@E_ACCOUNT    //相当first方法
    WHILE (@@fetch_status<>-1)  //如果不是记录尾开始遍历,相当于 not eof
     BEGIN
       xxxxxxx        //遍历操作
       FETCH NEXT FROM CURSOR1 INTO @E_CODE,@E_ACCOUNT //相当next方法   
     END
    END
    DEALLOCATE CURSOR1    //关闭
      

  12.   

    多谢了,不过我是用VC++开发的,而且是第一次接触SQL,能否提供VC下的代码?再次感谢!
    另外,我对自动编号字段的处理是按meigo(草莓)说的进行:
    首先字段选int整形数据类型
    在企业管理器中进入表的设计状态,选中要设置自动编号的字段,
    双击标识栏中的'否',变成'是'
    在表识栏下面那个文本框里写入你要自动编号的头一个编号,我设为1;
    再下面那个文本框中写入自动编号的增加量(默认值是1,自动加1)
    可为什么它不从1开始,而是从3000多开始??
      

  13.   

    我没用过VC,不好意思.我觉得,在SQLSERVER2000中,自动编号不从1开始有两中情况:一是种子数大于1
    二是在设置自动编号后有删除了全部记录,所以插入记录时就不从1开始了
      

  14.   

    推荐两种方法:
    方法一:
          删除你那个字段,重新添加一字段,设为自动编号(没实践过,试之前请先备份数据库:]  )
    方法二:将sql server数据库中的表转换到access中,在那里自动编号,不过好像只能从1开始编号哦,呵呵