MySQL使用內建函數來進行模糊搜尋(locate()等)

來源:互聯網
上載者:User

標籤:

常用的一共有4個方法,如下:1. 使用locate()方法

        1.1.普通用法:

              SELECT `column` from `table` where locate(‘keyword‘, `condition`)>0

         類似於 java 的 indexOf();不過 locate() 只要找到返回的結果都大於0(即使是查詢的內容就是最開始部分),沒有尋找到才返回0;

        1.2. 指定其實位置:

               SELECT LOCATE(‘bar‘, ‘foobarbar‘,5);  --> 7 (從foobarbar的第五個位置開始尋找)

2.使用instr()函數 (據說是locate()的別名函數)

       SELECT `column` from `table` where instr(`condition`, ‘keyword’ )>0

       唯一不同的是 查詢內容的位置不同,見SQL語句中過的keyword

3.使用position()方法,(據說也是locate()方法的別名函數,功能一樣) 

         SELECT `column` from `table` where position(‘keyword’ IN `condition`)

         不過它不再是通過傳回值來判斷,而是使用關鍵字 in

4.使用find_in_set()函數

       如: find_in_set(str,strlist),strlist必須要是以逗號分隔的字串

    如果字串str是在的strlist組成的N子串的字串列表,傳回值的範圍為1到N

SQL> SELECT FIND_IN_SET(‘b‘,‘a,b,c,d‘);+---------------------------------------------------------+| SELECT FIND_IN_SET(‘b‘,‘a,b,c,d‘)                       |+---------------------------------------------------------+| 2                                                       |+---------------------------------------------------------+1 row in set (0.00 sec) 

 

    總結: locate、position 和 instr 的差別只是參數的位置不同,同時locate 多一個起始位置的參數外,兩者是一樣的。

              find_in_set()是個比較特殊的存在,但它們都是返回要尋找的子字串 在 指定字串中的位置。

              速度上前3個比用 like 稍快了一點。(不過這四個函數都不能使用索引,這是個遺憾)

MySQL使用內建函數來進行模糊搜尋(locate()等)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.