Mysql字串擷取函式

酷越發表於2013-09-25

今天建檢視時,用到了MySQL中的字串擷取,很是方便。

感覺上MySQL的字串函式擷取字元,比用程式擷取(如PHP或JAVA)來得強大,所以在這裡做一個記錄,希望對大家有用。 
函式: 
1、從左開始擷取字串 
left(str, length) 
說明:left(被擷取欄位,擷取長度) 
例:select left(content,200) as abstract from my_content_t 
2、從右開始擷取字串 
right(str, length) 
說明:right(被擷取欄位,擷取長度) 
例:select right(content,200) as abstract from my_content_t 
3、擷取字串 
substring(str, pos) 
substring(str, pos, length) 
說明:substring(被擷取欄位,從第幾位開始擷取) 
substring(被擷取欄位,從第幾位開始擷取,擷取長度) 
例:select substring(content,5) as abstract from my_content_t 
select substring(content,5,200) as abstract from my_content_t 
(注:如果位數是負數 如-5 則是從後倒數位數,到字串結束或擷取的長度) 
4、按關鍵字擷取字串 
substring_index(str,delim,count) 
說明:substring_index(被擷取欄位,關鍵字,關鍵字出現的次數) 
例:select substring_index("blog.jb51.net","。",2) as abstract from my_content_t 
結果:blog.jb51 
(注:如果關鍵字出現的次數是負數 如-2 則是從後倒數,到字串結束) 

函式簡介:

SUBSTRING(str,pos) , SUBSTRING(str FROM pos) SUBSTRING(str,pos,len) , SUBSTRING(str FROM pos FOR len)

不帶有len 引數的格式從字串str返回一個子字串,起始於位置 pos。帶有len引數的格式從字串str返回一個長度同len字元相同的子字串,起始於位置 pos。 使用 FROM的格式為標準 SQL 語法。也可能對pos使用一個負值。假若這樣,則子字串的位置起始於字串結尾的pos 字元,而不是字串的開頭位置。在以下格式的函式中可以對pos 使用一個負值。

相關文章