Long T-SQL查询 - 需要帮助优化

时间:2015-08-06 19:23:07

标签: sql sql-server query-optimization

下面的查询花了一分多钟才能完成对大约12,000行的表的执行。我知道为什么这种速度很慢,因为每个操作有多个操作,但我不知道如何以降低成本的方式编写它。提前谢谢。

SELECT 
    para.ParagraphGUID, 
    para.Content,
    ChapterNbr, 
    ParagraphNbr,
    paragraphStatus, 
    para.CreateDate, 
    dv.VersionNumber 
FROM 
    tblParagraph para 
LEFT OUTER JOIN 
    tblDocumentVersion dv on dv.ParagraphGUID = para.ParagraphGUID
WHERE 
    ChapterNbr = '1' AND dv.VersionNumber = '14' 
    AND para.ParagraphGUID IN 
        (SELECT TOP 1 one.ParagraphGUID 
         FROM tblParagraph one 
         LEFT OUTER JOIN tblDocumentVersion onedv ON onedv.ParagraphGUID = one.ParagraphGUID 
         WHERE one.ParagraphNbr = para.ParagraphNbr 
           AND one.ChapterNbr = '1' AND onedv.VersionNumber = '14' 
         ORDER BY one.CreateDate DESC)
ORDER BY 
    order by ParagraphNbr ASC

1 个答案:

答案 0 :(得分:1)

您的相关查询会针对外部查询返回的每一行执行,因此会产生性能损失,请使用row_number函数来获取您所需的内容,这样的内容......

WITH CTE AS (
SELECT para.ParagraphGUID, 
       para.Content,
       ChapterNbr, 
       ParagraphNbr,
       paragraphStatus, 
       para.CreateDate, 
       dv.VersionNumber,
       ROW_NUMBER() OVER (PARTITION BY para.ParagraphGUID ORDER BY para.CreateDate DESC) rn  
FROM tblParagraph para 
LEFT OUTER JOIN tblDocumentVersion dv on dv.ParagraphGUID = para.ParagraphGUID
                                     AND ChapterNbr = '1' 
                                     AND dv.VersionNumber = '14' 
)
SELECT * FROM CTE 
WHERE rn = 1
ORDER BY ParagraphNbr ASC