SQL Server查询优化

时间:2011-09-22 03:10:16

标签: sql sql-server-2005

我继承了为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 

1 个答案:

答案 0 :(得分:0)

我与同样的查询处于类似的位置。以下是一些提示:

  • 查看查询计划以确保您拥有正确的索引。
  • 我不确定MSSQL是否围绕DATEDIFF()进行优化,但如果不能,则可以预先计算阈值日期并将其转换为BETWEEN子句。
  • 如果您不需要按照ROW_NUMBER()子句中的所有列进行排序,请删除它们。这可能允许您在更简单的查询上进行分页,然后只需获取您返回的25行所需的额外数据。

另外,像这样重写两个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 

这应该使查询优化器表现得更好。