[精讚] [會員登入]
3102

[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

你可能感興趣的文章

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

[Mysql/Mariadb] 全文檢索 fulltext index 關於 MySQL 的全文檢索

[MySQL/Mariadb] console 將查詢結果輸出到檔案 在mysql 的console中該如何將查詢結果輸出到檔案?

[Mysql/Mariadb] 查看使用狀態,抓出可疑慢查詢SQL 當Mysql 的負載loading飆高時,除了重新啟動外,如果想對症下藥,那該怎麼處理?

[Docker] Mariadb-Galera出現Incorrect definition of table mysql.column_stats:'hist_type'及 'histogram' 使用docker的Mariadb-galera出現'hist_type'及 'histogram'型別錯誤的解決方法。

group by的語法在mysql升級後後就不正常了,怎麼回事? ONLY_FULL_GROUP_BY這個變數是怎樣,讓我原本可以用的語法失效了?

隨機好文

Linux shell 的date表示法 linux下SHELL中的date表示法

UTF8中文字/全形一覽 快速查詢urf-8的中文字,共計13246中文字(5401常用字+7652罕用字+日文或編號),292全形符號,27半形符號。

TFTP Server 安裝及使用 讓設備的網路設定檔或是韌體經由TFTP拷備出來,操作的方法

[CodeIgniter3] 解決無法上傳特定檔案(.sb2)的問題 上傳時出現The filetype you are attempting to upload is not allowed,要怎麼解決?

[CodeIgniter 3] 資料庫的使用方法整理2/2 CI3 承襲 CI2,有很多的builder class可以用,依各人的使用習慣,有人喜歡一堆sql字串,有人喜歡用helper