如果我可以优化此查询,请告诉我?

时间:2014-05-07 05:15:14

标签: mysql sql optimization

是否有人建议优化此查询:

SELECT COUNT(client_id) FROM (
  SELECT client_id FROM `cdr` WHERE 
    (DATE(start) BETWEEN '2014-04-21' AND '2014-04-25') AND 
    `service` = 'test' 
    GROUP BY client_id  
    HAVING SUM(duration) > 300 
)as t1

问题是,内部查询会扫描数百万行并返回数千行,这会使主查询变得懒惰。

感谢。

3 个答案:

答案 0 :(得分:2)

尝试以下查询,避免搜索功能,因为它不使用索引并杀死性能。必须将“开始”列编入索引。

SELECT COUNT(client_id) FROM (
  SELECT client_id FROM `cdr` WHERE 
    (start BETWEEN '2014-04-21 00:00:00' AND '2014-04-25 23:59:59') AND 
    `service` = 'test' 
    GROUP BY client_id  
    HAVING SUM(duration) > 300 
)as t1

答案 1 :(得分:1)

为什么不呢?我在某处读到了将日期直接与<或者>比两者之间的工作速度更快。

SELECT Count(client_id) FROM `cdr` 
WHERE DATE(start) >=  '2014-04-21' 
    AND DATE(start) <= '2014-04-25'
    AND  `service` = 'test' 
GROUP BY client_id  
HAVING SUM(duration) > 300 

在sql中进行子查询背后的逻辑是什么?

答案 2 :(得分:0)

您可以使用直接查询而不是像

这样的子查询
SELECT COUNT(client_id) FROM `cdr` 
WHERE (DATE(start) BETWEEN '2014-04-21' AND '2014-04-25') 
    AND `service` = 'test' 
GROUP BY client_id  
HAVING SUM(duration) > 300