like查询语句索引使用
<header class="Post-Header" style="color: rgb(18, 18, 18); font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", "PingFang SC", "Microsoft YaHei", "Source Han Sans SC", "Noto Sans CJK SC", "WenQuanYi Micro Hei", sans-serif; background-color: rgb(255, 255, 255);">








like查询语句索引使用
</header>1 年前 · 来自专栏 菜鸟爱码
- 数据准备
- like查询案例分析
- 问题优化
- 案例总结
一、数据准备
使用索引可以提高数据库查询的速度,但是在like查询语句中索引又该怎么使用呢?不妨通过sql的执行计划来看下:
创建一张表:

创建复合索引:

二、like查询案例分析
explain select name,age,sex from t_user where name like '%楠%'

我们从执行计划中可以看到 '%楠%' 模糊匹配的sql查询语句采用的是全表扫描,并没有使用到索引;
explain select name,age,sex from t_user where name like '楠%';

从执行计划中可以看出'楠%' 模糊匹配的sql查询语句查询时使用了我们创建的索引并且类型为range;
explain select name,age,sex from t_user where name like '%楠';

从执行计划中可以看到 '%楠' 模糊匹配的sql查询语句采用的是全表扫描,并没有使用到索引;
案例结果:结论上看模糊匹配 '%x%' 与'%x' 的查询语句都不会用到我们创建的索引,只有 'x%'的方式索引才有效;技术的角度上说模糊查询尽量使用'x%' 的方式来避免索引失效;但是在实际的开发中并不是这样,'%x%' 恰恰是我们在开发中使用频次最高的一个模糊匹配方式,我们并不会因为 '%x%' 性能问题而去牺牲产品逻辑;那么该如何避免因使用 '%x%' 导致的索引失效呢?
三、问题优化
重新创建覆盖索引 idx_t_user_name_age_sex

explain select name,age,sex from t_user where name like'%楠%';

再看下我们的执行计划,这次 '%楠%' 查询不在是全表扫描,而是用到了我们新创建的索引idx_t_user_name_age_sex;
explain select name,age,sex from t_user where name like'楠%';

执行计划中发现 '楠%' 模糊查询使用到的索引并没有变化;
explain select name,age,sex from t_user where name like'%楠';

这次 '%楠' 查询也不是全表扫描,也用到了我们新创建的索引idx_t_user_name_age_sex;
四、案例总结
我们使用模糊查询时, '%x%' 与'%x' 有可能会使索引失效,我们可以采用创建覆盖索引的方式来解决我们模糊查询索引失效的问题;
发布于 2020-06-20 09:58
#GE#