我继承了为SQL Server中的分页设计的这个地狱般的查询。
它只获得了25条记录,但根据SQL Profiler,它执行了8091次读取,208次写入并需要74毫秒。希望它更快一点。 ORDER BY列deployDate
上有一个索引。
任何人对如何优化它都有任何想法?
SELECT TOP 25
textObjectPK, textObjectID, title, articleCredit, mediaCredit,
commentingAllowed,deployDate,
container, mediaID, mediaAlign, fileName AS fileName, fileName_wide AS fileName_wide,
width AS width, height AS height,title AS mediaTitle, extension AS extension,
embedCode AS embedCode, jsArgs as jsArgs, description as description, commentThreadID,
totalRows = Count(*) OVER()
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY textObjects.deployDate DESC) AS RowNumber,
textObjects.textObjectPK, textObjects.textObjectID, textObjects.title,
textObjects.commentingAllowed, textObjects.credit AS articleCredit,
textObjects.deployDate,
containers.container, containers.mediaID, containers.mediaAlign,
media.fileName AS fileName, media.fileName_wide AS fileName_wide,
media.width AS width, media.height AS height, media.credit AS mediaCredit,
media.title AS mediaTitle, media.extension AS extension,
mediaTypes.embedCode AS embedCode, media.jsArgs as jsArgs,
media.description as description, commentThreadID,
TotalRows = COUNT(*) OVER ()
FROM textObjects WITH (NOLOCK)
INNER JOIN containers WITH (NOLOCK)
ON containers.textObjectPK = textObjects.textObjectPK
AND (containers.containerOrder = 0 or containers.containerOrder = 1)
INNER JOIN LUTextObjectTextObjectGroup tog WITH (NOLOCK)
ON textObjects.textObjectPK = tog.textObjectPK
AND tog.textObjectGroupID in (3)
LEFT OUTER JOIN media WITH (NOLOCK)
ON containers.mediaID = media.mediaID
LEFT OUTER JOIN mediaTypes WITH (NOLOCK)
ON media.mediaTypeID = mediaTypes.mediaTypeID
WHERE (((version = 1)
AND (textObjects.textObjectTypeID in (6))
AND (DATEDIFF(minute, deployDate, GETDATE()) >= 0)
AND (DATEDIFF(minute, expireDate, GETDATE()) <= 0))
OR ( (version = 1) AND (textObjects.textObjectTypeID in (6))
AND (DATEDIFF(minute, deployDate, GETDATE()) >= 0)
AND (expireDate IS NULL)))
AND deployEnglish = 1
) tmpInlineView
WHERE RowNumber >= 51
ORDER BY deployDate DESC
答案 0 :(得分:0)
我与同样的查询处于类似的位置。以下是一些提示:
另外,像这样重写两个LEFT OUTER JOINs
:
LEFT OUTER JOIN
(
media WITH (NOLOCK)
LEFT OUTER JOIN mediaTypes WITH (NOLOCK)
ON media.mediaTypeID = mediaTypes.mediaTypeID
)
ON containers.mediaID = media.mediaID
这应该使查询优化器表现得更好。