MySql查询计划选择具有较少行的索引来检查但执行速度要慢得多

时间:2013-06-25 13:32:40

标签: mysql indexing sql-execution-plan

我有一个简单的查询 - 它只查看一个表,并且可以选择2列进行索引,ErrorTypeId(指向大约20个唯一值的查找表)和DateOccurred(可以包含任何日期的datetime列)在里面)。

在大多数情况下它很好但在某些情况下查询会超时。调查一下,所选择的索引(ErrorTypeId)在其计划中的行数少于另一个(DateOccurred),但由于某种原因,运行时间比手动强制使用其他索引要长得多。

/* This execution plan has fewer rows than the second one - and as a result this is
 * the one chosen.  But it is much much slower.
 */
EXPLAIN
SELECT * FROM my_log_table
WHERE DateOccurred BETWEEN '2013-06-11 00:00:00' AND '2013-06-22 00:00:00' AND ErrorTypeId = 4
ORDER BY DateOccurred DESC
LIMIT 1000;


/* Many more rows - but much much quicker to execute. 
 * Is it the spread of data across pages?  Is there a
 * way other than USE/FORCE INDEX to improve execution plan?
 */
EXPLAIN
SELECT * FROM my_log_table USE INDEX (DateOccurred_Index)
WHERE DateOccurred BETWEEN '2013-06-11 00:00:00' AND '2013-06-22 00:00:00' AND ErrorTypeId = 4
ORDER BY DateOccurred DESC
LIMIT 1000;

当有更多行要查看时,为什么第二个查询会更快?

有没有办法帮助MySql选择更快的索引而不使用USE / FORCE索引?

1 个答案:

答案 0 :(得分:0)

查询速度慢的原因是索引效率低下。

(ErrorTypeId, DateOccurred)上添加综合索引,您不需要任何强制或提示。