欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MySQL中Like模糊查詢速度太慢該如何進(jìn)行優(yōu)化

 更新時(shí)間:2021年12月14日 10:59:25   作者:小王java  
在業(yè)務(wù)場(chǎng)景中經(jīng)常會(huì)用到like模糊查詢,但是大家都知道,like是用不到索引的,所以當(dāng)數(shù)據(jù)量非常大時(shí),速度會(huì)非常慢,這篇文章主要給大家介紹了關(guān)于MySQL中Like模糊查詢速度太慢該如何進(jìn)行優(yōu)化的相關(guān)資料,需要的朋友可以參考下

一、前言:

我建了一個(gè)《學(xué)生管理系統(tǒng)》,其中有一張學(xué)生表和四張表(小組表,班級(jí)表,標(biāo)簽表,城市表)進(jìn)行聯(lián)合的模糊查詢,效率非常的低,就想了一下如何提高like模糊查詢效率問題

注:看本篇博客之前請(qǐng)查看:Mysql中如何查看Sql語句的執(zhí)行時(shí)間

二、第一個(gè)思路建索引

1、like %keyword 索引失效,使用全表掃描。

2、like keyword% 索引有效。

3、like %keyword% 索引失效,使用全表掃描。

使用explain測(cè)試了一下:

原始表(注:案例以學(xué)生表進(jìn)行舉例)

-- 用戶表
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)
);

建立索引

#create index 索引名 on 表名(列名);                 
create index username on t_users(username);

like %keyword% 索引失效,使用全表掃描

explain select id,username,password,real_name,sex,birth,mobile,head_pic 
 from t_users where username like '%h%';

like keyword% 索引有效。

 explain select id,username,password,real_name,sex,birth,mobile,head_pic 
 from t_users where username like 'wh%';

like %keyword 索引失效,使用全表掃描。

三、INSTR

這個(gè)我最開始都沒聽說過,今天查閱了一下資料,才知道有這個(gè)寶貝東西,

instr(str,substr)返回字符串str串中substr子串第一個(gè)出現(xiàn)的位置,沒有找到字符串返回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

比較兩個(gè)效率差距不大主要原因是數(shù)據(jù)較少,最好多準(zhǔn)備點(diǎn)原始數(shù)據(jù)進(jìn)行測(cè)試效果最佳

附:Like是否使用索引?

  1、like %keyword? ? 索引失效,使用全表掃描。但可以通過翻轉(zhuǎn)函數(shù)+like前模糊查詢+建立翻轉(zhuǎn)函數(shù)索引=走翻轉(zhuǎn)函數(shù)索引,不走全表掃描。

  2、like keyword%? ? 索引有效。

  3、like %keyword% 索引失效,也無法使用反向索引。

總結(jié)

到此這篇關(guān)于MySQL中Like模糊查詢速度太慢該如何進(jìn)行優(yōu)化的文章就介紹到這了,更多相關(guān)MySQL?Like模糊查詢慢優(yōu)化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論