[精讚] [會員登入]
3167

[Mysql/MariaDB] 使用 LOCATE, POSITION, INSTR來取代 like

“
[Mysql/MariaDB中使用LOCATE, POSITION, INSTR來取代 like的方法
„

分享此文連結 //n.sfs.tw/10603

分享連結 [Mysql/MariaDB] 使用 LOCATE, POSITION, INSTR來取代 like@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-24 17:44:15 最後編修
2017-01-13 01:49:48 By 張○○
 

自動目錄

Mysql 大家都會用這樣的語法:

SELECT `column` FROM `table` where `condition` like '%keyword%'

事實上,可以使用 locate 和 instr 這兩個函數來代替,例如要找出欄位 `condition`中是否有 keyword 關鍵字

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

如果locate回傳大於0,第一個字元位址為1,則表示該關鍵字存在。

或是使用 locate 的別名 position,只會回傳true/false
SELECT `column` from `table` where position('keyword' IN `condition`)

或是使用instr,和locate的參數相反。
SELECT `column` from `table` where instr(`condition`, 'keyword' )>0

locate、position 和 instr 的差別是參數的位置不同(請仔細看上例),三者差異不大。

locate還可以使用第三個參數:

範例:在`condition`中的第10個字開始尋找'keyword' 字串

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

速度上這兩個函數比用 like 稍快了一點(憑感覺)。

參考資料

[1] Mysql String Function http://dev.mysql.com/doc/refman/5.0/en/string-functions.html


原文 2010-06-19 03:19:49

END

你可能感興趣的文章

[Mysql/Mariadb] 建立使用者及資料庫 Mysql/Mariadb建立使用者、刪除使用者、給予權限、建立資料庫

[mysqldump] Mysqldump時出現記憶體錯誤Out of memory 當進行 mysqldump 時出現 Out of memory (Needed xxxxx bytes) 的錯誤,該如何處理?

[MySQL/Mariadb] 正規表達式(regular express) mysql的正規表達式很詭異,很不能接受

[Mysql/Mariadb] Left Join 和 Right Join 合併表單 SQL語法中的 Left Join 和 Right Join 很常用,但是我常會忘記,所以寫下來備忘。

[Mysql] 使用索引來加速搜尋 只要是常常用到搜索條件的欄位,就應該把它設成索引鍵,有無設定的速度差可能會好幾倍

[Mysql] 使用union合併兩個表 mysql合併兩個表的方法,使用union

隨機好文

使用Google尋找你的手機 這近發現google竟然可以用來找android的手機,而且不需要經過什麼設定或安裝軟體。

正則表達式:Email名稱防止連續輸入點(.)及下底線(_) Email的名稱中要允許特殊符號,但又不允許連續出現的正則表達式

[SIP] Kphone安裝記錄 Kphone是2008年當時ipv6剛要推廣時,唯一支援IPv6的公用網路電話,安裝的全記錄..

[HTLM5] 表單時間日期date/time輸入類型 介紹HTML5和時間有關的輸入類型date/datetime/datetime-local/month/time/week

[MariaDB] Centos 7安裝mariadb + apache + php + phpmyadmin Centos 7安裝mariadb+apache+php+phpmyadmin