mysql是根据什么来选择是不是使用一个索引呢?
表df的name字段上有索引。
看下面的两个查询:
mysql> explain select name from df where name like 'a%';
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | df | ALL | name | NULL | NULL | NULL | 6272 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1 row in set (0.00 sec)
mysql> explain select name from df where name like 'abc%';
+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | df | range | name | name | 768 | NULL | 1 | Using where |
+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+
1 row in set (0.00 sec)
第一个查询,type字段是ALL,mysql进行了全表扫描。
第二个,type字段是range,mysql使用了name这个索引。
------------------------------------------------------------------------------------------
这是因为,mysql是cost模型的。根据cost的不同,选择不同的执行方式。
在这里,优化器计算二者的开销,会发现like 'a%'使用索引的开销会比不适用索引的开销更大,所以就没有使用索引了。而like 'abc%'则相反。
----------------------
这里有详细的介绍。