MySQL无法识别WHERE中的日期时间索引

时间:2014-01-03 17:53:35

标签: mysql sql datetime indexing

我要做的是索引一个人的名字和他们出生的日期。

表格如下:

CREATE TABLE test
(
 id INT NOT NULL AUTO_INCREMENT,
 fname VARCHAR(10) NOT NULL,
 sname VARCHAR(10) NOT NULL,
 age INT NOT NULL,
 born DATETIME NOT NULL,

 PRIMARY KEY(id),
 INDEX name_age(fname, sname, age),
 INDEX name_date(fname, born)
)

然而,索引无法在where语句中识别,如:

mysql> EXPLAIN SELECT * 
    -> FROM  `test` 
    -> WHERE fname =  "coby"
    -> AND born
    -> BETWEEN  "1900-05-02 06:23:00"
    -> AND  "2100-05-02 06:23:00";
+----+-------------+-------+------+--------------------+----------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys      | key      | key_len | ref   | rows | Extra       |
+----+-------------+-------+------+--------------------+----------+---------+-------+------+-------------+
|  1 | SIMPLE      | test  | ref  | name_age,name_date | name_age | 12      | const |   45 | Using where |
+----+-------------+-------+------+--------------------+----------+---------+-------+------+-------------+
1 row in set (0.00 sec)

然而,它在声明的顺序中得到承认:

mysql> EXPLAIN SELECT * 
    -> FROM  `test` 
    -> WHERE fname =  "coby"
    -> ORDER BY born;
+----+-------------+-------+------+--------------------+-----------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys      | key       | key_len | ref   | rows | Extra       |
+----+-------------+-------+------+--------------------+-----------+---------+-------+------+-------------+
|  1 | SIMPLE      | test  | ref  | name_age,name_date | name_date | 12      | const |   45 | Using where |
+----+-------------+-------+------+--------------------+-----------+---------+-------+------+-------------+
1 row in set (0.00 sec)

如何创建它以便在where语句中识别索引?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:3)

识别索引 ,如第一个possible_keys语句的结果列EXPLAIN中所示。它恰好发生,对于45行,另一个索引产生相同或更好的查询计划:日期范围的选择性接近于零。

ORDER BY是另一双鞋:当你使用索引不仅用于选择,而且用于订购时,它现在变得有用。