MySQL优化:创建了索引,但索引没有起作用
1 or、in(待确认)
2 like '%abc' 或者 like‘%abc%’
3 where num/2=100 或者 subString(a,1,3)='ab'
4 where id !=2 或者 where id <> 2
5 where name is null 和 is not null
6 字符类型没加引号
7 使用select *
8 索引列有函数
9 order by索引字段顺序不当导致索引失效
2查索引explain 使用
explain select * from test where code='01' and age=2
1表的读取顺序。(对应id)
2数据读取操作的操作类型。(对应select_type)
3哪些索引可以使用。(对应type)
type:这是重要的列,显示连接使用了何种类型。从最好到最差的连接类型为const、eq_reg、ref、range、index和ALL
type显示的是访问类型,是较为重要的一个指标,结果值从好到坏依次是:system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL
一般来说,得保证查询至少达到range级别,最好能达到ref。
4哪些索引可以使用。(对应possible_keys)
5哪些索引被实际使用。(对应key)
实际使用的索引。如果为NULL,则没有使用索引。很少的情况下,MYSQL会选择优化不足的索引。这种情况下,可以在SELECT语句中使用USE INDEX(indexname)来强制使用一个索引或者用IGNORE INDEX(indexname)来强制MYSQL忽略索引
6表直接的引用。(对应ref)
7每张表有多少行被优化器查询。(对应rows)
3 索引设计的几个建议:
优先使用唯一索引,能够快速定位
为常用查询字段建索引
为排序、分组和联合查询字段建索引
一张表的索引数量不超过5个
表数据量少,可以不用建索引
尽量使用占用空间小的字段建索引
用idx_或unx_等前缀命名索引,方面查找
删除没用的索引,因为它会占一定空间