我创建了一个有近800,000条记录的表。
mysql> describe automation_search_test;
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| filename | text | YES | MUL | NULL | |
| site | text | YES | MUL | NULL | |
| script | text | YES | MUL | NULL | |
| station | text | YES | MUL | NULL | |
| result | text | YES | MUL | NULL | |
| failcode | text | YES | MUL | NULL | |
| stbmodel | text | YES | MUL | NULL | |
| rid | text | YES | MUL | NULL | |
| testdate | text | YES | MUL | NULL | |
+----------+---------+------+-----+---------+----------------+
在filename
列上添加索引
mysql> show index from automation_search_test;
+------------------------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+------------------------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| automation_search_test | 0 | PRIMARY | 1 | id | A | 767825 | NULL | NULL | | BTREE | |
| automation_search_test | 1 | ast_fname_idx | 1 | filename | A | 767825 | 255 | NULL | YES | BTREE | |
+------------------------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
对于WHERE条件,针对filename
列的查询使用索引没有问题。
但是,针对filename
列的简单SELECT查询会忽略索引
mysql> explain select filename from automation_search_test;
+----+-------------+------------------------+------+---------------+------+---------+------+--------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------------+------+---------------+------+---------+------+--------+-------+
| 1 | SIMPLE | automation_search_test | ALL | NULL | NULL | NULL | NULL | 767825 | |
+----+-------------+------------------------+------+---------------+------+---------+------+--------+-------+
如何强制使用此索引?
答案 0 :(得分:3)
由于没有SELECT
条件的WHERE
会返回该列中的所有值,因此索引无法执行任何操作。
这有点像为什么当我想阅读整本书时,为什么不使用教科书背面的索引。
答案 1 :(得分:2)
听起来好像在寻找覆盖指数。只有在包含完整数据的情况下,覆盖索引(可以满足整个查询而不需要访问表的索引)才有效。在您的示例中,filename
上的索引最多包含255个字符。如果实际文件名较长,则不会包含整个数据,因此它不是该查询的覆盖索引。
如果filename
的类型为varchar(255)
,那么它会使用索引作为示例查询。