📄 sql server开发技巧-4.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body bgcolor="#000000" text="#FFFFFF">
<font color="#009900">SQL快马加鞭 </font>
<p> </p>
<p> 我们在使用SQL时往往会陷入一个误区,即太关注于所得的结果是否正确,而忽略了不同的实现方法之间可能存在的性能差异,这种性能差异在大型的或是复杂的数据库环境中(如联机事务处理OLTP或决策支持系统DSS)中表现得尤为明显。笔者在工作实践中发现,不良的SQL往往来自于不恰当的索引设计、不充分的连接条件和不可优化的
where子句。在对它们进行适当的优化后,其运行速度有了明显的提高!下面我将从这 三个方面分别进行总结。</p>
<p> 为了更直观地说明问题,所有实例中的SQL运行时间均经过测试,不超过1秒的均表示为(<1秒)。测试环境</p>
<p>主机:HP LH II <br>
主频:330MHz <br>
内存:128MB <br>
操作系统:Oper server 5.0.4 <br>
数据库:Sybase 11.0.3 <br>
</p>
<p>一、不合理的索引设计<br>
例:表record有620000行,试看在不同的索引下,下面几个SQL的运行情况:</p>
<p>1.在date上建有一个非群集索引<br>
select count(*) from record where date>'19991201' and date<'19991214'
<br>
and amount>2000 --(25秒)<br>
select date, sum(amount) from record group by date --(55秒)<br>
select count(*) from record where date>'19990901' and place in<br>
('BJ','SH') --(27秒)</p>
<p>分析:date上有大量的重复值,在非群集索引下,数据在物理上随机存放在数据页上,在范围查找时,必须执行一次表扫描才能找到这一范围内的全部行。</p>
<p>2.在date上的一个群集索引<br>
select count(*) from record where date>'19991201' and date<'19991214'
<br>
and amount>2000 --(14秒)<br>
select date,sum(amount) from record group by date --(28秒)<br>
select count(*) from record where date>'19990901' and place in<br>
('BJ','SH') --(14秒)</p>
<p>分析:在群集索引下,数据在物理上按顺序排在数据页上,重复值也排列在一起,因而在范围查找时,可以先找到这个范围的起末点,且只在这个范围内扫描数据页,避免了大范围扫描,提高了查询速度。</p>
<p>3.在place、date、amount上的组合索引<br>
select count(*) from record where date>'19991201' and date<'19991214'
<br>
and amount>2000 --(26秒)<br>
select date,sum(amount) from record group by date --(27秒)<br>
select count(*) from record where date>'19990901' and place in<br>
('BJ’,'SH') --(<1秒)</p>
<p>分析:这是一个不很合理的组合索引,因为它的前导列是place,第一和第二条SQL没有引用place,因此也没有利用上索引;第三个SQL使用了place,且引用的所有列都包含在组合索引中,形成了索引覆盖,所以它的速度是非常快的。</p>
<p>4.在date、place、amount上的组合索引<br>
select count(*) from record where date>'19991201' and date<'19991214'
<br>
and amount>2000 --(<1秒)<br>
select date, sum(amount) from record group by date --(11秒)<br>
select count(*) from record where date>'19990901' and place in<br>
('BJ','SH') --(<1秒)</p>
<p>分析:这是一个合理的组合索引。它将date作为前导列,使每个SQL都可以利用索引,并且在第一和第三个SQL中形成了索引覆盖,因而性能达到了最优。</p>
<p></p>
<p></p>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -