一、索引的使用场景
1、全值匹配
通过主键索引查询
mysql> explain select * from t_goods where id = 1 \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t_goods
partitions: NULL
type: const
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: const
rows: 1
filtered: 100.00
Extra: NULL
1 row in set, 1 warning (0.00 sec)
可以看到这里查询数据使用了主键索引。
现在我们再创建一个索引。
ALTER Table t_goods ADD INDEX index_category_name(t_category_id,t_name);
这里为t_category_id与t_name创建了联合索引。
mysql> explain select * from t_goods where t_category_id = 1 and t_name = '手机' \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t_goods
partitions: NULL
type: ref
possible_keys: index_category_name
key: index_category_name
key_len: 208
ref: const,const
rows: 1
filtered: 100.00
Extra: NULL
1 row in set, 1 warning (0.00 sec)
这里的查询条件为t_category_id与t_name,所以查询时使用了联合索引index_category_name
2、查询范围
对索引的值进行范围查找
mysql> explain select * from t_goods where id >= 1 and id <=20 \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t_goods
partitions: NULL
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 15
filtered: 100.00
Extra: Using where
1 row in set, 1 warning (0.00 sec)
type: range
说明根据主键索引范围进行查询。这里 Extra: Using where
,说明MySQL按照主键确定范围后再回表查询数据。
3、匹配最左前缀
解释:也就是说,在使用索引时,MySQL优化器会根据查询条件使用该索引。只有满足这个匹配原则才会使用索引。例如过程创建的联合索引index_category_name(t_category_id, t_name)
,如果我跳过t_category_id
直接使用t_name
条件查询,那么这个查询将不会使用索引。
mysql> explain select * from t_goods where t_name='手机' \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t_goods
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 15
filtered: 10.00
Extra: Using where
1 row in set, 1 warning (0.00 sec)
可以看到这个查询并没有使用索引。