开发者

Datetime indexing in Mysql

Here is table

+------------+----------+------+-----+---------+-------+
| Field      | Type     | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| datecolumn | datetime | YES  | MUL | NULL    |       |
+------------+----------+------+-----+---------+-------+

Data in table

+---------------------+
| datecolumn          |
+---------------------+
| 2007-01-01 00:00:00 |
| 2007-01-03 00:00:00 |
| 2008-01-03 00:00:00 |
| 2009-01-03 00:00:00 |
| 2010-01-01 00:00:00开发者_开发知识库 |
| 2010-01-02 00:00:00 |
| 2010-01-03 00:00:00 |
+---------------------+



EXPLAIN select * from test_date_index use key (datecolumn) where datecolumn>='2010-01-02 00:00:00';
+----+-------------+-----------------+-------+---------------+------------+---------+------+------+--------------------------+
| id | select_type | table           | type  | possible_keys | key        | key_len | ref  | rows | Extra                    |
+----+-------------+-----------------+-------+---------------+------------+---------+------+------+--------------------------+
|  1 | SIMPLE      | test_date_index | index | datecolumn    | datecolumn |  9     | NULL |    7 | Using where; Using index |
+----+-------------+-----------------+-------+---------------+------------+---------+------+------+--------------------------+
1 row in set (0.00 sec)

Why mysql use 7 rows to retreive 1 row?

Thanks in advance!


It does use the index.

It (most probably) does not use the range access, since the table has so few records that searching for the first record of the range is in fact more expensive than just traversing the index and filtering the values.

When you add more values into the table, the range access is applied (since it's considered cheaper now) and COUNT shows 1, since you only have one record satisfying the condition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜