mysql 模糊查詢

2022-09-17 19:33:15 字數 2648 閱讀 1048

mysql 中一般使用like 來進行模糊查詢,但like 的效率非常的低,容易導致全表掃瞄,因此不推薦使用。

那有木有其他的方法代替like來進行模糊查詢呢?

下面簡單介紹下各個方法的使用情況

測試物件  content 表

select count(mlzm_content.id) from mlzm_content

資料量: 33034 條資訊

like

select id,title from mlzm_content where title like '

%美女%

'

結果:294 條記錄

耗時: 0.0130 秒

select id,title from mlzm_content where title like '

%模特%

'

結果:10 條記錄

耗時: 0.0550 秒

結論:但查詢到結果集的資料量少的時候like耗時會增加,即總資料量不變,結果越少耗時約大

instr

語法:instr(str, substr)

select id,title from mlzm_content where instr(title,'

美女')>0;

結果:294 條

耗時:0.0150 秒

instr(str, substr) 與locate(substr, str) 類似,只是引數的位置變了

locate

語法:locate(substr, str)

select id,title from mlzm_content where locate('

美女',title)>0;

結果:294 條

耗時: 0.0150 秒

select id,title from mlzm_content where locate('

模特',title)>0

結果:10條

耗時: 0.0760 秒

普通用法:

select `column` from `table` where locate('

keyword

', `condition`)>0

類似 js 的 indexof(); locate() (返回的結果為子串在字串中第一次出現的位置,因為從1開始計數,因此只要匹配結果均大於0),沒有查詢到才返回0;

指定位置查詢:

select locate('

bar', '

foobarbar

',5); --> 7 (從foobarbar的第五個位置開始查詢)

返回 'bar' 在 'foobarbar' 第一次出現的位置(這裡限制了從第5位後面開始查詢,因此結果為7),位置下標是從1開始計數的。

position

語法:position(substr in str)

select id,title from mlzm_content where position('

美女' in title);

結果:294 條

耗時: 0.0150 秒

小結:locate()、position()、instr()類似,執行效率前2這基本一致,instr()要比前2這稍微快一點。但3者的執行效率都要比like 的略低。

(可能是資料量不大,真實的效率有待考察,後續會利用大資料來進行效率測試後再做定論。這裡的效率問題並不是一定用哪個就要好,一切都要根據實際需求測試後再做定論。)

find_in_set

語法:find_in_set(str, strlist)

select id,title from mlzm_content where find_in_set('

美女',title);

結果:1 條

耗時:  0.0470 秒

select id,title from mlzm_content where find_in_set('

模特',title)

結果:1 條

耗時:  0.0460 秒

select find_in_set('

b','

a,b,c,d

');

耗時:  0.0020 秒

總結:

like是廣泛的模糊匹配,字串中沒有分隔符,find_in_set 是精確匹配,字段值以英文」,」分隔,find_in_set查詢的結果要小於like查詢的結果。

find_in_set  的執行效率在同樣的結果集下,要比like高。

mysql模糊查詢 MYSQL模糊查詢

mysql提供標準的sql模式匹配,以及一種基於象unix實用程式如vi grep和sed的擴充套件正規表示式模式匹配的格式。一 sql模式 sql的模式匹配允許你使用 匹配任何單個字元,而 匹配任意數目字元 包括零個字元 在 mysql中,sql的模式預設是忽略大小寫的。下面顯示一些例子。注意在你...

mysql模糊查詢索引 MySQL模糊查詢全文索引

全文索引 mysql front dump 2.5 host localhost database test server version 4.0.12 nt log table structure for table t3 create table t3 name char 12 not null...

mysql 正反模糊查詢 mysql模糊查詢

mysql 使用內建函式進行模糊查詢 locate,position,instr,find in set 1 locate substr str,pos 方法 2 position substr in field 方法 3 instr str substr 方法 4 find in set str1...