在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