商城首页欢迎来到中国正版软件门户

您的位置:首页 > 编程开发 >MySQL中如何使用SUBSTRING()函数

MySQL中如何使用SUBSTRING()函数

  发布于2023-05-03 阅读(0)

扫一扫,手机访问

SUBSTRING()

SUBSTRING(str,pos)SUBSTRING(str FROM pos)SUBSTRING(str,pos,len)以及SUBSTRING(str FROM pos FOR len)函数都可以用于返回从指定位置 pos 开始的子串,len 表示返回子串的长度;pos 为 0 表示返回空字符串。例如:

SELECT SUBSTRING('MySQL字符串函数', -2) AS str1,
       SUBSTRING('MySQL字符串函数', -5, 3) AS str2;
str1  |str2  |
------+------+
函数  |字符串 |

位置参数 pos 可以为负数,此时返回的子串从字符串右侧第 pos 个字符开始。例如:

SELECT LEFT('MySQL字符串函数',5) AS str1,
       RIGHT('MySQL字符串函数',5) AS str2;
str1 |str2     |
-----+---------+
MySQL|字符串函数|

另外,SUBSTR()MID()函数都是 SUBSTRING() 函数的同义词,也支持以上 4 种形式。

LEFT(str,len)函数返回字符串 str 左侧的 len 个字符,RIGHT(str,len)函数返回字符串 str 右侧的 len 个字符。例如:

SELECT LEFT('MySQL字符串函数',5) AS str1,
       RIGHT('MySQL字符串函数',5) AS str2;
str1 |str2     |
-----+---------+
MySQL|字符串函数|

SUBSTRING_INDEX(str,delim,count)函数返回第 count 个分隔符 delim 之前的子串。如果 count 为正数,从左侧开始计数并返回左侧的所有字符;如果 count 为负数,从右侧开始计数并返回右侧的所有字符。例如:

SELECT SUBSTRING_INDEX('张三;李四;王五', ';', 2) AS str1,
       SUBSTRING_INDEX('张三;李四;王五', ';', -2) AS str2;
str1    |str2    |
--------+--------+
张三;李四|李四;王五|
本文转载于:https://www.yisu.com/zixun/496499.html 如有侵犯,请联系admin@zhengruan.com删除

热门关注