一、前言:
我建了一個《學生管理系統》,其中有一張學生表和四張表(小組表,班級表,標簽表,城市表)進行聯合的模糊查詢,效率非常的低,就想了一下如何提高like模糊查詢效率問題
注:看本篇博客之前請查看:mysql中如何查看sql語句的執行時間
二、第一個思路建索引
1、like %keyword 索引失效,使用全表掃描。
2、like keyword% 索引有效。
3、like %keyword% 索引失效,使用全表掃描。
使用explain測試了一下:
原始表(注:案例以學生表進行舉例)
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), -- 真實姓名 real_name varchar (50), -- 性別 1表示男 0表示女 sex int , -- 出生年月日 birth date , -- 手機號 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
這個我最開始都沒聽說過,今天查閱了一下資料,才知道有這個寶貝東西,
instr(str,substr)
:返回字符串str串中substr子串第一個出現的位置,沒有找到字符串返回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 |
比較兩個效率差距不大主要原因是數據較少,最好多準備點原始數據進行測試效果最佳
附:like是否使用索引?
1、like %keyword 索引失效,使用全表掃描。但可以通過翻轉函數+like前模糊查詢+建立翻轉函數索引=走翻轉函數索引,不走全表掃描。
2、like keyword% 索引有效。
3、like %keyword% 索引失效,也無法使用反向索引。
總結
到此這篇關于mysql中like模糊查詢速度太慢該如何進行優化的文章就介紹到這了,更多相關mysql like模糊查詢慢優化內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_44385486/article/details/121916824