MySQL 字符串截取SUBSTRING()函數

2022-02-17 15:16 更新

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(被截取字段,從第幾位開始截?。?nbsp;
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("hgci.cn",".",2) as abstract from wiki_user 

結果:www.w3cschool
(注:如果關鍵字出現的次數是負數 如-2 則是從后倒數,到字符串結束) 

函數簡介:

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

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


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號