mysql 索引與最佳化like查詢

來源:互聯網
上載者:User

標籤:from   效率   word   使用   data   str   keyword   執行   指標   

詳見:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt101

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值的降低。

 

mysql 索引與最佳化like查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.