select 语句是否用到了索引,可以使用mysql的 explain 来执行后查看。下面做一个比较基础的总结。
索引常用类型:
Normal 普通索引
unique 唯一索引
fulltext 文本索引
添加索引语句:
alter table t_user ADD INDEX idx_name (name);
explain select 结果如下图所示(参考示例)
说下字段的意思:
table:
表示数据来自哪张表
type:
最好到最差的类型: const , eq_ref,ref,range,index 和ALL
- ALL: 表示走的全表扫描
- ref:连接查询(如left join)不是主键或唯一约数的索引(普通索引),根据索引匹配的记录越少越好
- eq_ref :连接查询(如left join) 使用了主键为主键或唯一约数的时候 ,如 where user.id = teacher.id
- index : 用在fulltext字段,
- range: 索引范围,比如 > , <
in: 测试,使用如下explain select * from t_user u where u.id in (1,2,3) ,如果1,2,3有记录,则走range索引,如果 1,2,3其中有一个没有对应的数据库表记录,则走all ,如果in 其中一个则使用const,效率最高。
not in :
explain select * from t_user u where u.id not in (1,2)
not in 字段(主键或唯一约数)如果多条记录走的all, 如果not in 一个 则走range索引
not in 字段(非索引或 普通索引),通过测试后发现,则不管有1个还是多个,都走的ALL
possible_keys
显示查询可能用到的索引(一个或者多个或为null) ,不一定被查询实际使用,仅供参考
Key:
实际使用的索引字段,如果为NULL,表示没有使用索引
key_len :
索引的长度(字节数),不丢失精度经情况下,值越小越好
ref:
索引哪一列或者常量(const)
rows:
表示找到所需记录需要读取的行数,值越大越不好
extra :
using where: 使用where 过滤
那些where条件会导致索引无效
- where 条件有 != ,Mysql无法使用索引
- where 字句使用mysql函数,索引将无效
如:
explain select * from t_user t where upper(name)='yzy' 不走索引,
explain select * from t_user t where name='yzy' 走索引
- like索引, like 'xxx%'有效, like '%xx%' 索引无效
如:
explain select * from t_user where name like 'y%'; -- 走range 索引
explain select * from t_user where name like '%y%';
- 字符串使用'',不使用''不走索引
- 在where 子句中使用is not null 不走索引
explain select * from t_user where name is not null; -- 全表扫描,type:ALL
explain select * from t_user where name is null; -- 走索引,type:ref
- 如果条件中有or不走索引 ,建议少用or,如果要用or则or的每个列都要加索引,数据量少的时候,possible_keys会出现可能得索引列
explain select * from t_user where (name ='yzy' or pwd='1'); -- 走ALL,建议少用or