如何使用索引优化mysql查询?

时间:2014-11-14 07:26:47

标签: mysql indexing query-optimization query-performance

我有以下查询,需要3秒才能运行。

SELECT c.kpi_name as kpi ,count(*) as cnt ,c.only_date as date 
FROM cellwise_performance c 
WHERE c.kpi_name ='DL Cell Throughput (Mbps)' 
      AND c.only_date BETWEEN '2014-06-10' AND '2014-11-05' AND c.kpi_value>=5   
GROUP BY c.kpi_name,month(c.only_date)

union all

SELECT c.kpi_name as kpi ,count(*) as cnt ,c.only_date as date 
FROM cellwise_performance c 
WHERE c.kpi_name ='DL Cell Throughput (Mbps)' 
      AND c.only_date BETWEEN '2014-06-10' AND '2014-11-05' AND c.kpi_value between 2 and 5 
GROUP BY c.kpi_name,month(c.only_date)

union all

SELECT c.kpi_name as kpi ,count(*) as cnt ,c.only_date as date 
FROM cellwise_performance c 
WHERE c.kpi_name ='DL Cell Throughput (Mbps)' 
      AND c.only_date BETWEEN '2014-06-10' AND '2014-11-05' AND c.kpi_value<2 
GROUP BY c.kpi_name,month(c.only_date);

解释查询计划是:

---+---------+-------+-------+----------------------------------------------+
| id | select_type  | table        | type | possible_keys                | key      | key_len | ref   | rows  | Extra                                        |
+----+--------------+--------------+------+------------------------------+----------+---------+-------+-------+----------------------------------------------+
|  1 | PRIMARY      | c            | ref  | kpi_name,kpi_value,only_date | kpi_name | 203     | const | 72552 | Using where; Using temporary; Using filesort |
|  2 | UNION        | c            | ref  | kpi_name,kpi_value,only_date | kpi_name | 203     | const | 72552 | Using where; Using temporary; Using filesort |
|  3 | UNION        | c            | ref  | kpi_name,kpi_value,only_date | kpi_name | 203     | const | 72552 | Using where; Using temporary; Using filesort |
| NULL | UNION RESULT | <union1,2,3> | ALL  | NULL                         | NULL     | NULL    | NULL  |  NULL |

请帮我优化此查询。

2 个答案:

答案 0 :(得分:1)

ALTER TABLE cellwise_performance ADD INDEX (kpi_name, kpi_value, only_date);

您需要一个能够捕获所有所搜索列的索引,或者它无法优化所有内容。

答案 1 :(得分:1)

好的我做了类似的事情,查询就像魅力一样 -

select x.kpi,x.rating,date(x.date) as month,Count(*) `cnt` 
from ( select c.kpi_name as kpi ,
              case when c.kpi_value<2 then 0 
                   when c.kpi_value >= 5 then 2 
                   else 1 
              end `rating` ,
              c.only_date as date 
       from cellwise_performance c 
       where c.kpi_name ='DL Cell Throughput (Mbps)' 
         and c.only_date>='2014-06-10') as `x` 
 group by x.kpi,x.rating,month(x.date);