一、索引对哪个有效?
where,order,group,join字段
二、口诀
全值匹配我最爱,最左前缀要遵守;
带头大哥不能死,中间兄弟不能断;
索引列上少计算,范围之后全失效;
like百分写最后,覆盖索引不写星;
join连接类型同,order条件非表达式;
不等空值or和'0/1',索引失效要少用。
口诀示例:
1、https://blog.csdn.net/wuseyukui/article/details/72312574
2、在JOIN操作中(需要从多个数据表提取数据时),MYSQL只有在主键和外键的数据类型相同时才能使用索引,否则即使建立了索引也不会使用
3、在ORDER BY操作中,MYSQL只有在排序条件不是一个查询条件表达式的情况下才使用索引。尽管如此,在涉及多个数据表的查询里,即使有索引可用,那些索引在加快ORDER BY操作方面也没什么作用。
4、如果某个数据列里包含着许多重复的值,就算为它建立了索引也不会有很好的效果。比如说,如果某个数据列里包含了净是些诸如“0/1”或“Y/N”等值,就没有必要为它创建一个索引。
三、示例总结
where语句 | 索引是否被使用 |
where a=3 | Y,使用到a |
where a=3 and b=5 | Y,使用到a,b |
where a=3 and b=5 and c=4 | Y,使用到a,b,c |
where b=3 或 where c=4 或 where b=3 and c=4 | N |
where a=3 and c=5 | Y,使用到a,但是c不可以,b中间断了 |
where a=3 and b>4 and c=5 | Y,使用到a和b, c不能用在范围之后,b断了 |
where a=3 and b like 'kk%' and c=4 | Y,使用到a,b,c |
where a=3 and b like '%kk' and c=4 | Y,使用到a |
where a=3 and b like '%kk%' and c=4 | Y,使用到a |
where a=3 and b like 'k%kk%' and c=4 | Y,使用到a,b,c |
where a>=5,<=9,>4,<10 | Y,但是必须查询值5,9都存在表中 |
where a in (5,6,7) | Y, a |
where a in (select id from t2 where c='cc') | N |
where a between 5 and 9 | Y,5,9都存在表中; N:5或9不在表中 |
where a=3 or b=5 | N |
where a !=3或a<>3 | N |
where a is null或where a is not null | N |
转载:
https://blog.csdn.net/wuseyukui/article/details/72312574
https://www.jb51.net/article/37190.htm
MYSQL索引无效和索引有效的详细介绍
https://blog.csdn.net/s1040342522/article/details/88638363
in查询
https://www.jianshu.com/p/20361fe96f0a
>,<,between都可以使用索引