MySQL中如何使用SUBSTRING()函数

54次阅读
没有评论

共计 1023 个字符,预计需要花费 3 分钟才能阅读完成。

丸趣 TV 小编给大家分享一下 MySQL 中如何使用 SUBSTRING() 函数,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

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 |
--------+--------+
张三; 李四 | 李四; 王五 |

看完了这篇文章,相信你对“MySQL 中如何使用 SUBSTRING() 函数”有了一定的了解,如果想了解更多相关知识,欢迎关注丸趣 TV 行业资讯频道,感谢各位的阅读!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-07-13发表,共计1023字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)