为什么MySQL查询不会使用索引?

时间:2014-07-15 14:39:55

标签: mysql indexing

我尝试了几种不同的方法,但我无法弄清楚为什么我的查询不会使用索引。

EXPLAIN SELECT 
    allocationdate,
    SUM(linepersonal) as recpts
FROM
    c1.recpt #force index (rbadateptype) #force index (rbADate)
WHERE
    allocationdate BETWEEN 20120101 AND 20140630 
        AND ptype = 3
GROUP BY YEAR(allocationdate);

不强制索引:

+----+-------------+--------+------+----------------------+------+---------+------+----------+----------------------------------------------+
| id | select_type | table  | type | possible_keys        | key  | key_len | ref  | rows     | extra                                        |
+----+-------------+--------+------+----------------------+------+---------+------+----------+----------------------------------------------+
| 1  | SIMPLE      | recptb | ALL  | rbADate,rbADatePtype | NULL | NULL    | NULL | 23186904 | Using where; Using temporary; Using filesort |
+----+-------------+--------+------+----------------------+------+---------+------+----------+----------------------------------------------+

强制使用rbadateptype:

+----+-------------+--------+------+----------------------+----------------+---------+------+----------+----------------------------------------------+
| id | select_type | table  | type | possible_keys        | key            | key_len | ref  | rows     | extra                                        |
+----+-------------+--------+------+----------------------+----------------+---------+------+----------+----------------------------------------------+
| 1  | SIMPLE      | recptb | ALL  | rbADate,rbADatePtype | rbAdatePtype | 9       | NULL | 8199594| Using where; Using temporary; Using filesort |
+----+-------------+--------+------+----------------------+----------------+---------+------+----------+----------------------------------------------+

`allocationDate` date DEFAULT NULL,
`pType` int(10) DEFAULT NULL,
KEY `rbADate` (`allocationDate`),
KEY `rbAdatePtype` (`allocationDate`,`patType`),

我无法解释的一件有趣的事情是,日期的索引如何表示它需要查看7,784,810条记录,但日期和ptype上的综合索引需要查看8,199,594。

我刚注意到的一个更有趣的事情是,使用rbAdate索引时,它表示当select count(1)返回21,610,791时需要查看23,186,904条记录。

0 个答案:

没有答案