Mysql 中字符串的截取 left/right/substring/substring_index

一.从左开始截取字符串

用法:left(str, length),即:left(被截取字符串, 截取长度)

mysql> SELECT LEFT('hello,world',3);
+-----------------------+
| LEFT('hello,world',3) |
+-----------------------+
| hel                   |
+-----------------------+
1 row in set (0.00 sec)

二.从右开始截取字符串

用法:right(str, length),即:right(被截取字符串, 截取长度)

mysql> SELECT right('hello,world',3);
+------------------------+
| right('hello,world',3) |
+------------------------+
| rld                    |
+------------------------+
1 row in set (0.00 sec)

三.截取特定长度的字符串

用法:

  • substring(str, pos),即:substring(被截取字符串, 从第几位开始截取)
  • substring(str, pos, length),即:substring(被截取字符串,从第几位开始截取,截取长度)

pos 正向起始值为1,反向起始值为-1

#1.从字符串的第3个字符开始读取直至结束
mysql> SELECT substring('hello,world',3);
+----------------------------+
| substring('hello,world',3) |
+----------------------------+
| llo,world                  |
+----------------------------+
1 row in set (0.00 sec)

#2.从字符串的倒数第3个字符开始读取直至结束
mysql> SELECT substring('hello,world',-3);
+-----------------------------+
| substring('hello,world',-3) |
+-----------------------------+
| rld                         |
+-----------------------------+
1 row in set (0.01 sec)

#3.从字符串的第3个字符开始,只取5个字符
mysql> SELECT substring('hello,world',3,5);
+------------------------------+
| substring('hello,world',3,5) |
+------------------------------+
| llo,w                        |
+------------------------------+
1 row in set (0.00 sec)

#4.从字符串的倒数第3个字符开始,只取5个字符
mysql> SELECT substring('hello,world',-3,5);
+-------------------------------+
| substring('hello,world',-3,5) |
+-------------------------------+
| rld                           |
+-------------------------------+
1 row in set (0.00 sec)

四.按关键字进行读取

用法:

  • substring_index(str, delim, count),即:substring_index(被截取字符串,关键字,关键字出现的次数)
#1.截取第二个“|”之前的所有字符
mysql> SELECT substring_index('1|2|3|4|5','|',2);
+------------------------------------+
| substring_index('1|2|3|4|5','|',2) |
+------------------------------------+
| 1|2                                |
+------------------------------------+
1 row in set (0.00 sec)

#2.截取倒数第二个“|”之后的所有字符
mysql> SELECT substring_index('1|2|3|4|5','|',-2);
+-------------------------------------+
| substring_index('1|2|3|4|5','|',-2) |
+-------------------------------------+
| 4|5                                 |
+-------------------------------------+
1 row in set (0.00 sec)

#3.如果关键字不存在,则返回整个字符串
mysql> SELECT substring_index('1|2|3|4|5|','-',2);
+-------------------------------------+
| substring_index('1|2|3|4|5|','-',2) |
+-------------------------------------+
| 1|2|3|4|5|                          |
+-------------------------------------+
1 row in set (0.00 sec)

 其他举例:

将1|2|3 替换为a=1 b=2 c=3

SELECT concat('a=',substring_index('1|2|3','|',1),
' b=',substring_index(substring_index('1|2|3','|',2),'|',-1),
' c=',substring_index('1|2|3','|',-1));

 

posted @ 2021-03-03 16:33  声声慢43  阅读(1812)  评论(0编辑  收藏  举报