MySQL中Like模糊查询速度太慢该如何进行优化
转载自: https://www.zhangshengrong.com/p/boNwZxnOaw/
一、前言:
mysql进行联合的模糊查询,效率非常的低,就想了一下如何提高like模糊查询效率问题
注:看本篇博客之前请查看:Mysql中如何查看Sql语句的执行时间
二、第一个思路建索引
使用explain测试了一下:
1、like %keyword 索引失效,使用全表扫描。
explain select id,username,password,real_name,sex,birth,mobile,head_pic
from t_users where username like '%wh';
2、like keyword% 索引有效。
explain select id,username,password,real_name,sex,birth,mobile,head_pic
from t_users where username like 'wh%';
3、like %keyword% 索引失效,使用全表扫描。
explain select id,username,password,real_name,sex,birth,mobile,head_pic
from t_users where username like '%wh%';
原始表(注:案例以学生表进行举例)
-- 用户表
create table t_users(
id int primary key auto_increment,
-- 用户名
username varchar(20),
-- 密码
password varchar(20),
-- 真实姓名
real_name varchar(50),
-- 性别 1表示男 0表示女
sex int,
-- 出生年月日
birth date,
-- 手机号
mobile varchar(11),
-- 上传后的头像路径
head_pic varchar(200)
);
建立索引
#create index 索引名 on 表名(列名);
create index username on t_users(username);
三、INSTR
这个我最开始都没听说过,今天查阅了一下资料,才知道有这个宝贝东西,
instr(str,substr):返回字符串str串中substr子串第一个出现的位置,没有找到字符串返回0,否则返回位置(从1开始)
#instr(str,substr)方法
select id,username,password,real_name,sex,birth,mobile,head_pic
from t_users
where instr(username,'wh')>0 #0.00081900
#模糊查询
select id,username,password,real_name,sex,birth,mobile,head_pic
from t_users
where username like 'whj'; # 0.00094650
四、主要区别关系参考
链接: https://blog.csdn.net/weixin_44028926/article/details/106301863