优化SQL查询sql

时间:2012-11-16 14:40:14

标签: sql performance sql-server-2008 tsql

我还需要帮助加快这个查询,在LIVE db上花费25分钟,在TEST db上花费1秒。

这是经过一些修改后,我最初查询数据库服务器几百次从主页查询的每一行使用while循环从php页面获取数据,然后我尝试使用临时表来创建一个过程返回数据,我在45分钟后取消执行。所以我试过了。

我想可以在“从NurQueryResults选择top 1”查询中进行内部联接,但我无法弄明白。我得到了结果但不是最新的结果,我做了一个“按t1.time,t2.time,t3.time ....订购”它确实有t1最近的结果在顶部,但它返回了更多的结果应该有的。

SELECT o.VisitID                                          AS VisitID,
       (SELECT TOP 1 Response
        FROM   NurQueryResults
        WHERE  QueryID = 'OEDTCAT'
               AND VisitID = o.VisitID
        ORDER  BY DateTime DESC)                          AS PPN,
       (SELECT TOP 1 Response
        FROM   NurQueryResults
        WHERE  QueryID = 'OEDTMEAT'
               AND VisitID = o.VisitID
        ORDER  BY DateTime DESC)                          AS MEAT,
       (SELECT TOP 1 Response
        FROM   OeOrderQueries
        WHERE  QueryID = 'OESPMOD'
               AND VisitID = o.VisitID
        ORDER  BY RowUpdateDateTime DESC)                 AS SPMOD,
       (SELECT TOP 1 Response
        FROM   OeOrderQueries
        WHERE  QueryID = 'OERT3'
               AND VisitID = o.VisitID
        ORDER  BY RowUpdateDateTime DESC)                 AS SPMOD2,
       (SELECT TOP 1 Response
        FROM   NurQueryResults
        WHERE  QueryID = 'OEDTDECUB'
               AND VisitID = o.VisitID
        ORDER  BY DateTime DESC)                          AS DECUB,
       (SELECT TOP 1 Response
        FROM   NurQueryResults
        WHERE  QueryID = 'OEALL2'
               AND VisitID = o.VisitID
        ORDER  BY DateTime DESC)                          AS FOODALL,
       o.OrderedProcedureName,
       o.OrderDateTime,
       a.RoomID,
       a.BedID,
       a.Name,
       a.Sex,
       DATEDIFF(year, a.ComputedBirthDateTime, GETDATE()) AS Age
FROM   OeOrders o
       INNER JOIN AdmVisits a
         ON o.VisitID = a.VisitID
            AND o.Category = 'DIET'
            AND o.StatusChoice = 'S'
            AND a.Status = 'ADM IN'
ORDER  BY o.VisitID,
          o.OrderDateTime DESC 

2 个答案:

答案 0 :(得分:0)

我只是想知道,当你做这样的事情时结果如何:

SELECT
    o.VisitID AS VisitID,
    PPN.Response
FROM OeOrders o
JOIN AdmVisits a
    ON o.VisitID = a.VisitID
    AND o.Category = 'DIET'
    AND o.StatusChoice = 'S'
    AND a.Status = 'ADM IN'
join
(
    SELECT 
        Response, 
        VisitID, 
        ROW_NUMBER() OVER(ORDER BY DateTime DESC) AS MyRowNumber 
    FROM NurQueryResults 
    WHERE QueryID = 'OEDTCAT'
) AS PPN
    on o.VisitID = PPN.VisitID
    and PPN.MyRowNumber = 1

这不是您的整个查询,而只是第一个获取PPN列的子查询。

如果您更改此JOIN之类的所有子查询,它是否有任何性能提升?

答案 1 :(得分:0)

启用执行计划并查看结果。它可能表明您缺少索引或某种性质的东西。 说到索引,检查所涉及的索引的碎片,如果它们很高,请考虑重建它们。我最近取得了相当多的成功,通过上述过程,在1-3秒内完成生产运行2分钟的程序。