索引與優化like查詢
1. like %keyword 索引失效,使用全表掃描。但可以通過翻轉函數+like前模糊查詢+建立翻轉函數索引=走翻轉函數索引,不走全表掃描。2. like keyword% 索引有效。
3. like %keyword% 索引失效,也無法使用反向索引。
====================================================================
1. 使用下面的函數來進行模糊查詢,如果出現的位置〉0,表示包含該字符串。
查詢效率比like要高。
如果: table.field like ‘%AAA%’ 可以改為 locate (‘AAA’ , table.field) > 0
LOCATE(substr,str)
POSITION(substr IN str)
返回子串substr在字符串str第一個出現的位置,如果substr不是在str里面,返回0。
使用instr
select count(*) from table t where instr(t.column,’xx’)> 0
這種查詢效果很好,速度很快。
2. 查詢%xx的記錄
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′
在執行的時候,執行計划顯示,消耗值,io值,cpu值均非常大,原因是like后面前模糊查詢導致索引失效,進行全表掃描
解決方法:這種只有前模糊的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′)
使用翻轉函數+like前模糊查詢+建立翻轉函數索引=走翻轉函數索引,不走全掃描。有效降低消耗值,io值,cpu值這三個指標,尤其是io值的降低。
來源:https://www.cnblogs.com/hubing/p/4469058.html