MySql模糊查询
常規(guī)like的使用限制:
1. like %keyword :索引失效,使用全表掃描。但可以通過翻轉(zhuǎn)函數(shù)+like前模糊查詢+建立翻轉(zhuǎn)函數(shù)索引=走翻轉(zhuǎn)函數(shù)索引,不走全表掃描。
2. like keyword% :索引有效。3. like %keyword% :索引失效,也無法使用反向索引。
MySql使用內(nèi)置函數(shù)實現(xiàn)模糊查詢:
1. 使用locate()方法
1.1.普通用法:
1.2. 指定其實位置:
SELECT LOCATE('bar', 'foobarbar',5); --> 7
? ? 從foobarbar的第五個位置開始查找?
2.使用instr()函數(shù) (據(jù)說是locate()的別名函數(shù))
3.使用position()方法
? ?據(jù)說也是locate()方法的別名函數(shù),功能一樣?
4.使用find_in_set()函數(shù)
? ?如: find_in_set(str,strlist),strlist必須要是以逗號分隔的字符串
? ?如果字符串str是在的strlist組成的N子串的字符串列表,返回值的范圍為1到N
find_in_set()是個比較特殊的存在,但它們都是返回要查找的子字符串 在 指定字符串中的位置。速度上前3個比用 like 稍快了一點(不過這四個函數(shù)都不能使用索引,這是個遺憾)。
查詢%xx的記錄優(yōu)化
select count(c.c_ply_no) as COUNT from Policy_Data_All c, Item_Data_All i where c.c_ply_no = i.c_ply_no and i.C_LCN_NO like '%245' 在執(zhí)行的時候,執(zhí)行計劃顯示,消耗值,io值,cpu值均非常大,原因是like后面前模糊查詢導(dǎo)致索引失效,進(jìn)行全表掃描。
解決方法:
? ? 這種只有前模糊的sql可以改造如下寫法
select count(c.c_ply_no) as COUNT from Policy_Data_All c, Item_Data_All i where c.c_ply_no = i.c_ply_no and reverse(i.C_LCN_NO) like reverse('%245')使用翻轉(zhuǎn)函數(shù)+like前模糊查詢+建立翻轉(zhuǎn)函數(shù)索引=走翻轉(zhuǎn)函數(shù)索引,不走全掃描。有效降低消耗值,io值,cpu值這三個指標(biāo),尤其是io值的降低。
轉(zhuǎn)載于:https://www.cnblogs.com/archermeng/p/7537257.html
總結(jié)
- 上一篇: mac vagrant 虚拟机nfs挂载
- 下一篇: (poj)1064 Cable mas