怎样解决查询速度慢的问题?(100分)

  • 主题发起人 主题发起人 xdenver
  • 开始时间 开始时间
X

xdenver

Unregistered / Unconfirmed
GUEST, unregistred user!
用DELPHI6 的TQUERY 控件来对一个SYBASE数据库进行查询统计。统计的项目有30项之多。
程序的部分代码如下:
with Query1 do
begin
Close;
SQL.Clear;
SQL.Add('Select count(*) as 当天发机 from fcash where casfrq=:montha');
ParamByName('montha').asstring :=DateTimeToStr(Date());
Prepare;
Open;
Edit8.Text:=Query1.fieldbyname('当天发机').AsString;
end;

with Query1 do
begin
//Close;
SQL.Clear;
SQL.Add('Select count(*) as 当天取消 from fcash where casfrq=:montha and CAJF<>''正常交付''');
ParamByName('montha').asstring :=DateTimeToStr(Date());
Prepare;
Open;
Edit6.Text:=Query1.fieldbyname('当天取消').AsString;
end;

//在修机器 3-7天
With Query1 do
begin
//Close;
SQL.Clear;
SQL.Add('select count(*) as zx1 from fuser as a,fstold as b ');
SQL.Add('where (a.usdh not in(select cadh from fcash)) and b.OLDZT<>''待返'' and b.oldjsrq is null ');
SQL.ADD('and b.jldh=a.usdh and b.oldzt=''在修'' and datediff(day,a.usrq,getdate())>=3');
SQL.ADD('and datediff(day,a.usrq,getdate())<=7');
Prepare;
open;
Edit7.Text:=Query1.fieldbyname('zx1').AsString;
end;

//在修机器 8-14天
With Query1 do
begin
//Close;
SQL.Clear;
SQL.Add('select count(*) as zx2 from fuser as a,fstold as b ');
SQL.Add('where (a.usdh not in(select cadh from fcash)) and b.OLDZT<>''待返'' and b.oldjsrq is null ');
SQL.ADD('and b.jldh=a.usdh and b.oldzt=''在修'' and datediff(day,a.usrq,getdate())>=8');
SQL.ADD('and datediff(day,a.usrq,getdate())<=14');
Prepare;
open;
Edit9.Text:=Query1.fieldbyname('zx2').AsString;
end;

//在修机器 >14天
With Query1 do
begin
//Close;
SQL.Clear;
SQL.Add('select count(*) as zx3 from fuser as a,fstold as b ');
SQL.Add('where (a.usdh not in(select cadh from fcash)) and b.OLDZT<>''待返'' and b.oldjsrq is null ');
SQL.ADD('and b.jldh=a.usdh and b.oldzt=''在修'' and datediff(day,a.usrq,getdate())>14');
Prepare;
open;
Edit10.Text:=Query1.fieldbyname('zx3').AsString;
end;


//难修机器 3-7天
With Query1 do
begin
//Close;
SQL.Clear;
SQL.Add('select count(*) as zx1 from fuser as a,fstold as b ');
SQL.Add('where (a.usdh not in(select cadh from fcash)) and b.OLDZT<>''待返'' and b.oldjsrq is null ');
SQL.ADD('and b.jldh=a.usdh and b.oldzt=''难修'' and datediff(day,a.usrq,getdate())>=3');
SQL.ADD('and datediff(day,a.usrq,getdate())<=7');
Prepare;
open;
Edit11.Text:=Query1.fieldbyname('zx1').AsString;
end;
就是对数据库统计需要的项目的合计数,这样查询速度非常慢,希望有哪位高人指点一下!
 
适当合并一些查询吧,不然每次只查询一项就遍历了全表.有些浪费
比如难修3-7,8-14,14以上的就可以合并,当天发机和当天取消的也可以合并
select
count( case when (datediff(day,a.usrq,getdate()) between 3 and 7) then B.oldzt) as zx1,
count( case when (datediff(day,a.usrq,getdate()) between 8 and 14) then B.oldzt) as zx2,
count( case when (datediff(day,a.usrq,getdate())>14) then B.oldzt) as zx3
from fuser as a,fstold as b where (a.usdh not in(select cadh from fcash)) and b.OLDZT<>''待返'' and b.oldjsrq is null and b.jldh=a.usdh and b.oldzt=''难修''

建议你根据实际情况情况写好几个存储过程,这样比较快,尽量少的反复查询
 
我看你对日期字段做关键字的查询比较多,你可以把表的casfrq字段做成聚集索引,速度很快很多.
 
re,支持楼上的,呵呵!
 
找经常的查询的字段找出来,建一个索引。
 
使用存储过程可以每天先进行
 
后退
顶部