我真的需要帮助加快SQL Server中的以下查询。现在我把它作为一个视图,但我不在乎它是一个视图还是一个函数,我只需要它将记录集返回到MS Access接口。查询需要11秒才能执行,但是通过它所经历的所有周期,我需要将其缩短到3秒或更短的时间。我试图索引我现在的视图,但不幸的是,如果我要索引任何东西,我不能使用AVG函数或使用HAVING子句。
SELECT tblFi.fldFN
,tblFc.fldFC
,tblFc.fldCity
,tblFc.fldState
,tblFi.fldIN
,tblAPL.fldPK
,tblAPL.fldCI
,AVG(tblAPD.fldND) AS fldND
FROM tblAPD
INNER JOIN tblAPL ON tblAPD.fldLK = tblAPL.fldLID
INNER JOIN tblUA ON tblAPD.fldUAK = tblUA.fldUAID
INNER JOIN tblUL ON tblUA.fldULK = tblUL.fldULID
INNER JOIN tblFi ON tblUL.fldFK = tblFi.fldFID
INNER JOIN tblFc ON tblFi.fldFAC = tblFc.fldFacID
GROUP BY tblFi.fldFN
,tblFc.fldFac
,tblFc.fldCity
,tblFc.fldState
,tblFi.fldIN
,tblAPL.fldPK
,tblAPL.fldCI
,tblAPL.fldPG
,tblAPD.fldIG
HAVING (tblAPL.fldCI <> 0)
AND (AVG(tblAPD.fldND) IS NOT NULL)
AND (tblAPL.fldPG = 1)
AND (tblAPD.fldIG = 0)
以下是表格(我只包括查询中引用的列的伪名称,然后是fld1,fld2,fld3,用于那些无关的表格)...
tblAPL
- 450万行,fldLID
上的聚集索引
fldLID... INT
fld1... FLOAT
fldCI... FLOAT
fldPK... BIGINT
fldPG... TINYINT
fld2... TINYINT
fld3... TINYINT
fld4... NVARCHAR(15)
fld5... DATETIME
fld6... TINYINT
fld7... TINYINT
tblAPD
- 1,200万行,fldDID
上的聚集索引
fldND... FLOAT
fldLK... INT
fldUAK... INT
fldIG... TINYINT
fld1... SMALLINT
fld2... SMALLINT
fld3... SMALLINT
fld4... NVARCHAR(20)
fld5... TINYINT
fldDID... INT
tblUA
- 850,000行,fldUAID
上的聚集索引
fldULK... INT
fldUAID... INT
fld1... NVARCHAR(10)
fld2... INT
fld3... NVARCHAR(15)
fld4... INT
fld5... TINYINT
fld6... NVARCHAR(10)
fld7... INT
fld8... TINYINT
fld9...TINYINT
fld10...TINYINT
tblUL
- 200,000行,fldULID
上的聚集索引
fldULID... INT
fldFK... INT
fld1... INT
fld2... INT
fld3... INT
fld4... NVARCHAR(15)
fld5... DATETIME
fld6... DATETIME
答案 0 :(得分:0)
您可以先添加SET NOCOUNT ON;这应该会加快它的速度。
答案 1 :(得分:0)
您是否尝试将HAVING子句更改为简单的WHERE子句?你真正能够转移到WHERE子句的唯一部分是第二行(带有AVG语句的那一行),对吧?这可能会加快速度,因为在生成整个结果集之前不会评估HAVING条件。
答案 2 :(得分:0)
SELECT tblFi.fldFN
,tblFc.fldFC
,tblFc.fldCity
,tblFc.fldState
,tblFi.fldIN
,tblAPL.fldPK
,tblAPL.fldCI
,AVG(tblAPD.fldND) AS fldND
FROM tblAPD (NOLOCK)
INNER JOIN tblAPL (NOLOCK) ON tblAPD.fldLK = tblAPL.fldLID
INNER JOIN tblUA (NOLOCK) ON tblAPD.fldUAK = tblUA.fldUAID
INNER JOIN tblUL (NOLOCK) ON tblUA.fldULK = tblUL.fldULID
INNER JOIN tblFi (NOLOCK) ON tblUL.fldFK = tblFi.fldFID
INNER JOIN tblFc (NOLOCK) ON tblFi.fldFAC = tblFc.fldFacID
GROUP BY tblFi.fldFN
,tblFc.fldFac
,tblFc.fldCity
,tblFc.fldState
,tblFi.fldIN
,tblAPL.fldPK
,tblAPL.fldCI
,tblAPL.fldPG
,tblAPD.fldIG
WHERE (tblAPL.fldCI <> 0)
AND (tblAPL.fldCI = 1)
AND (tblAPD.fldIG = 0)
HAVING (AVG(tblAPD.fldND) IS NOT NULL)
对(fldCI)和(fldIG)进行非聚集索引 希望你有一个所有外键的索引。