增加SQL查询性能

时间:2011-07-20 07:22:27

标签: sql sql-server performance query-tuning

SQL:

select distinct DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) as Date,
(select count(*) from Raw_Mats A where DateAdd(Day, DateDiff(Day, 0, A.Receive_date), 0)=DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0)) as Total,
(select count(*) from Raw_Mats B where DateAdd(Day, DateDiff(Day, 0, B.Receive_date), 0)=DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) and B.status='Solved') as Delivered,
(select count(*) from Raw_Mats C where DateAdd(Day, DateDiff(Day, 0, C.Receive_date), 0)=DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) and C.status='Pending') as UnDelivered
from Raw_Mats m where m.Receive_date between '2011-07-01' and '2011-07-21'

如何提高上述查询的性能。这需要44秒。想要不到10秒

由于

3 个答案:

答案 0 :(得分:3)

您有Receive_datestatus的索引吗? (不是每个的索引,合并)

此外:

  • 表中有4个触摸,这意味着查询将至少缩放为O(4n)。 通过使用COUNT(CASE),您可以删除DeliveredUnDelivered子查询
  • 也不需要简单计数子查询
  • 您需要GROUP BY。你的DISTINCT是一个解决这个问题的工作
  • BETWEEN为>=<=,这对于有时间的日期通常不正确

为了清楚起见,我在这里使用了一个子查询,但这并不重要:

select
   DateOnly as Date,
   COUNT(*) AS Total,
   COUNT(CASE WHEN status='Solved' THEN 1 END) AS Delivered,
   COUNT(CASE WHEN status='Pending' THEN 1 END) AS UnDelivered
from
   (
   SELECT
       DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) as DateOnly,
       status
   FROM
      Raw_Mats
   WHERE
      Receive_date >= '2011-07-01' AND Receive_date < '2011-07-21'
   ) T
 GROUP BY
   DateOnly

编辑,没有子查询。

我从一个子查询开始,因为我认为它比预期更复杂,并且不打算把它拿出来......

select
   DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) as Date,
   COUNT(*) AS Total,
   COUNT(CASE WHEN status='Solved' THEN 1 END) AS Delivered,
   COUNT(CASE WHEN status='Pending' THEN 1 END) AS UnDelivered
from
   Raw_Mats
WHERE
   Receive_date >= '2011-07-01' AND Receive_date < '2011-07-21'
GROUP BY
   DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0)

答案 1 :(得分:0)

分而治之:只需将sql的每个部分作为单独的语句进行尝试,您就会发现哪个部分很慢。如果您有子选择和函数,那么服务器很可能需要临时表来执行选择,如果您没有足够的内存(或大型数据集或配置您的SQL服务器来执行此操作),临时对象被交换到磁盘,这也使它变慢。

答案 2 :(得分:0)

查询太多子查!摆脱其中的一些,它会有所帮助。此外,您不应在sqls中使用双方的功能。

例如:

where DateAdd(Day, DateDiff(Day, 0, A.Receive_date), 0)=
              DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) 

在这种特定情况下,db引擎必须遍历所有行以评估DateDiff(Day, 0, A.Receive_date) and DateAdd(Day, DateDiff(Day, 0, A.Receive_date), 0),然后将其与右侧进行比较,这也是一个函数!这简直就是一场灾难。

另外,你有Receive_date的索引吗?如果没有添加它。