Mysql截取字符串


在Mysql中,有時候會用到截取字符串然后相互連接的情形,其中截取字符串用的是SUBSTRING操作,連接用的是CONCAT操作:

1. 直接截取

SELECT LEFT('what is your name? please tell me',5);  #從左開始截取字符串,left(str, length),即:left(被截取字符串, 截取長度)

SELECT RIGHT('what is your name? please tell me',9);  #從右開始截取字符串,right(str, length),即:right(被截取字符串, 截取長度)

2. SUBSTRING截取

SELECT SUBSTRING('what is your name? please tell me', 3, 7) as str1;  # 從字符串的第3個字符開始,取7個字符

SELECT SUBSTRING('what is your name? please tell me', -8);  # 從字符串的倒數第8個字符開始讀取直至結束,末尾是-1,往前依次是-2,-3,...

SELECT SUBSTRING('what is your name? please tell me', -8, 2); #2 表示截取長度為2的子串

3. 按關鍵字進行讀取,substring_index(str, delim, count),即:substring_index(被截取字符串,關鍵字,截取關鍵字的第幾個之前的部分)

# 截取第二個“m”之前的所有字符
SELECT SUBSTRING_INDEX('what is your name? please tell me', 'm', 2); # 輸出:'what is your name? please tell '

# 截取倒數第二個“m”之后的所有字符,其實就是先找出'm'號,然后對'm'進行index,找出該inde之前的所有字符;如果是負號,則反向,也是找該index之前的字符串
SELECT SUBSTRING_INDEX('what is your name? please tell me', 'm', -2);  # 輸出:'e? please tell me'

# 如果關鍵字不存在,則返回整個字符串
SELECT SUBSTRING_INDEX('what is your name? please tell me', 'good', 1);

4. 連接 concat

select CONCAT('陳情令','','斗羅大陸');

 

參考:https://www.cnblogs.com/heyonggang/p/8117754.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM