我有一个简单的查询 - 它只查看一个表,并且可以选择 2 个用于索引的列,一个 ErrorTypeId(指向一个包含大约 20 个唯一值的查找表)和 DateOccurred(一个可以包含任何日期的日期时间列) .
在大多数情况下这很好,但在某些情况下查询会超时。调查一下,选择的索引 (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;
当有更多行要查看时,为什么第二个查询更快?
有没有办法在不使用 USE/FORCE 索引的情况下帮助 MySql 选择更快的索引?