索引未在MySQL查询中使用

时间:2014-10-07 10:49:23

标签: mysql performance indexing

我已经编写了下面的查询,并且需要将近5分钟才能运行。我在表中有600万行数据,并且从执行计划中发现,即使表中的所有字段都有索引,我的查询也不会使用索引。

查询

SELECT 
  event_date as date,   
  (CAST('2014-05-31' AS DATE)- INTERVAL 5 MONTH + INTERVAL 1 DAY) AS FROM_DATE,
  COUNT(DISTINCT(IF( Column1 !=0 OR Column2!=0 OR Column3 !=0, account, NULL))) AS total_account1,
  COUNT(DISTINCT(IF( Column4 !=0 OR Column5 !=0 OR Column6!=0, account, NULL))) AS total_account2,
  COUNT(DISTINCT(IF( Column7 !=0 OR Column8 !=0 OR Column9!=0, account, NULL))) AS total_account3
FROM Table_name
WHERE cast(event_date as DATE) BETWEEN CAST('2014-05-31' AS DATE)- INTERVAL 5 MONTH and CAST('2014-05-31' AS DATE)
  AND cast(event_date as DATE) < NOW() - INTERVAL 2 DAY
GROUP BY MONTH(event_date)
上面的查询输出

“解释”是 -

+----+-------------+---------+------+---------------+------+---------+------+---------+-----------------------------+
| id | select_type | table   | type | possible_keys | key  | key_len | ref  | rows    | Extra                       |
+----+-------------+---------+------+---------------+------+---------+------+---------+-----------------------------+
|  1 | SIMPLE      | table_name | ALL  | NULL          | NULL | NULL    | NULL | 5764552 | Using where; Using filesort |
+----+-------------+---------+------+---------------+------+---------+------+---------+-----------------------------+

为什么我的查询没有使用可用的索引?

1 个答案:

答案 0 :(得分:0)

您可以明确强制引擎使用索引。

检查http://dev.mysql.com/doc/refman/5.1/en/index-hints.html