小编典典

MySQL日期时间索引不起作用

mysql

表结构:

+-------------+----------+------+-----+---------+----------------+
| Field       | Type     | Null | Key | Default | Extra          |
+-------------+----------+------+-----+---------+----------------+
| id          | int(11)  | NO   | PRI | NULL    | auto_increment |
| total       | int(11)  | YES  |     | NULL    |                |
| thedatetime | datetime | YES  | MUL | NULL    |                |
+-------------+----------+------+-----+---------+----------------+

总行数: 137967

mysql> explain select * from out where thedatetime <= NOW();
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table       | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
|  1 | SIMPLE      | out         | ALL  | thedatetime   | NULL | NULL    | NULL | 137967 | Using where |
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+

带有更多表联接的真实查询要更长得多,关键是,我无法使表使用datetime索引。如果要选择特定日期之前的所有数据,这对我来说将很难。但是,我注意到,如果选择较小的数据子集,则可以使MySQL使用索引。

mysql> explain select * from out where thedatetime <= '2008-01-01';
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
| id | select_type | table       | type  | possible_keys | key         | key_len | ref  | rows  | Extra       |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
|  1 | SIMPLE      | out         | range | thedatetime   | thedatetime | 9       | NULL | 15826 | Using where |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+

mysql> select count(*) from out where thedatetime <= '2008-01-01';
+----------+
| count(*) |
+----------+
|    15990 |
+----------+

那么,无论我放置什么日期,该如何确保MySQL将使用索引?


阅读 1632

收藏
2020-05-17

共1个答案

小编典典

一切都按预期进行。:)

有索引可以加快检索速度。他们使用索引查找来完成。

在你第一次查询中不使用索引,因为使用的是指数慢检索所有行,在这种情况下(lookup indexget rowlookup indexget row… x行数是那么慢get all rows==表扫描)

在第二个查询中,您只检索一部分数据,在这种情况下,表扫描要慢得多。

优化器的工作是使用RDBMS保留在索引上的统计信息来确定最佳计划。在第一种情况下,考虑了索引,但是计划者(正确地)将其丢弃。

编辑
你可能想读的东西像这样得到关于MySQL的查询规划的一些概念和关键字。

2020-05-17