开发者

Datetime indexing in Mysql

开发者 https://www.devze.com 2023-01-31 22:02 出处:网络
Here is table +------------+----------+------+-----+---------+-------+ Field| Type| Null | Key | Default | Extra |

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

精彩评论

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

关注公众号