一、前言:
我建了一個(gè)《學(xué)生管理系統(tǒng)》,其中有一張學(xué)生表和四張表(小組表,班級(jí)表,標(biāo)簽表,城市表)進(jìn)行聯(lián)合的模糊查詢,效率非常的低,就想了一下如何提高like模糊查詢效率問(wèn)題
注:看本篇博客之前請(qǐng)查看:mysql中如何查看sql語(yǔ)句的執(zhí)行時(shí)間
二、第一個(gè)思路建索引
1、like %keyword 索引失效,使用全表掃描。
2、like keyword% 索引有效。
3、like %keyword% 索引失效,使用全表掃描。
使用explain測(cè)試了一下:
原始表(注:案例以學(xué)生表進(jìn)行舉例)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
-- 用戶表 create table t_users( id int primary key auto_increment, -- 用戶名 username varchar (20), -- 密碼 password varchar (20), -- 真實(shí)姓名 real_name varchar (50), -- 性別 1表示男 0表示女 sex int , -- 出生年月日 birth date , -- 手機(jī)號(hào) mobile varchar (11), -- 上傳后的頭像路徑 head_pic varchar (200) ); |
建立索引
1
2
|
# create index 索引名 on 表名(列名); create index username on t_users(username); |
like %keyword% 索引失效,使用全表掃描
1
2
|
explain select id,username, password ,real_name,sex,birth,mobile,head_pic from t_users where username like '%h%' ; |
like keyword% 索引有效。
1
2
|
explain select id,username, password ,real_name,sex,birth,mobile,head_pic from t_users where username like 'wh%' ; |
like %keyword 索引失效,使用全表掃描。
三、instr
這個(gè)我最開始都沒(méi)聽說(shuō)過(guò),今天查閱了一下資料,才知道有這個(gè)寶貝東西,
instr(str,substr)
:返回字符串str串中substr子串第一個(gè)出現(xiàn)的位置,沒(méi)有找到字符串返回0,否則返回位置(從1開始)
1
2
3
4
5
6
7
8
|
#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 |
比較兩個(gè)效率差距不大主要原因是數(shù)據(jù)較少,最好多準(zhǔn)備點(diǎn)原始數(shù)據(jù)進(jìn)行測(cè)試效果最佳
附:like是否使用索引?
1、like %keyword 索引失效,使用全表掃描。但可以通過(guò)翻轉(zhuǎn)函數(shù)+like前模糊查詢+建立翻轉(zhuǎn)函數(shù)索引=走翻轉(zhuǎn)函數(shù)索引,不走全表掃描。
2、like keyword% 索引有效。
3、like %keyword% 索引失效,也無(wú)法使用反向索引。
總結(jié)
到此這篇關(guān)于mysql中l(wèi)ike模糊查詢速度太慢該如何進(jìn)行優(yōu)化的文章就介紹到這了,更多相關(guān)mysql like模糊查詢慢優(yōu)化內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_44385486/article/details/121916824