加速这个SQL查询

时间:2011-05-09 08:17:54

标签: sql performance

我有以下(相当遗留,一年或两年前做过)SQL查询。 SQL所在的网页(在ASP.NET中的SqlDataSource / GridView上使用)非常慢,我已经确定了这个查询的缓慢 - 看似是因为子选择。我已经尝试过使用连接来加快速度,但我无法让它工作。有任何想法吗?

我不会把整个查询放在这里,只是因为我在一台没有互联网访问权限的机器上工作,所以我无法复制和粘贴,而且大多数只是从主表中选择。

SELECT ..., 
       CASE 
         WHEN di.Total = di.Delivered THEN 'Received' 
         ELSE 'Not Received' END AS 'Status',
       ...
FROM Deliveries AS d 
  LEFT OUTER JOIN (
         SELECT Delivery, 
                COUNT(*) AS Total, 
                COUNT(CASE WHEN Status = 2 THEN 1 END) AS Delivered 
         FROM DeliveryItems 
         GROUP BY Delivery
  ) AS di ON d.ID = di.Delivery

任何提示?

1 个答案:

答案 0 :(得分:0)

SELECT Delivery, 
       COUNT(*) AS Total, 
       COUNT(CASE WHEN Status = 2 THEN 1 END) AS Delivered 
FROM DeliveryItems 
GROUP BY Delivery

这部分可以通过抛弃CASE声明来改进。也许尝试连接两次,一次针对总计数,一次针对过滤计数。

SELECT ..., 
       CASE 
         WHEN d2.Total = d1.Delivered THEN 'Received' 
         ELSE 'Not Received' END AS 'Status',
       ...
FROM Deliveries AS d 

LEFT OUTER JOIN (

SELECT Delivery,
       COUNT(*) AS Delivered
FROM DeliveryItems
WHERE Status = 2
GROUP BY Delivery ) d1 ON d.Id = d1.Delivery

LEFT OUTER JOIN (

SELECT Delivery,
       COUNT(*) AS Total
FROM DeliveryItems
GROUP BY Delivery ) d2 ON d.ID = d2.Delivery