4

我真的需要帮助加快 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-- 1200 万行,聚集索引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
4

3 回答 3

0

您是否尝试过将 HAVING 子句更改为简单的 WHERE 子句?您真正不能移至 WHERE 子句的唯一部分是第二行(带有 AVG 语句的那一行),对吗?这可能会加快速度,因为在生成整个结果集之前不会评估 HAVING 标准。

于 2014-02-03T21:48:55.197 回答
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) 上创建一个非聚集索引希望你有一个所有外键的索引。

于 2014-02-10T14:55:37.730 回答
0

您可以从添加 SET NOCOUNT ON 开始;这应该会加快它的速度。

于 2013-10-20T23:29:43.663 回答