substring, substr
从指定位置提取字符,并返回指定长度的子字符串。
语法
VARCHAR substr(VARCHAR str, pos[, len])
参数
str
:必需,要提取字符的字符串。必须是 VARCHAR 值。pos
:必需,一个整数,指定起始位置。请注意,字符串中的第一个字符是 1,而不是 0。- 如果
pos
为 0,则返回空字符串。 pos
可以是负整数。在这种情况下,此函数从字符串的末尾开始提取字符。请参见示例 2。- 如果
pos
指定的位置超出字符串的范围,则返回空字符串。请参见示例 3。
- 如果
len
:可选,一个正整数,指定要提取的字符数。- 如果指定了
len
,此函数将从pos
指定的位置开始提取len
个字符。 - 如果未指定
len
,此函数将提取从pos
开始的所有字符。请参见示例 1。 - 如果
len
超过匹配字符的实际长度,则返回所有匹配的字符。请参见示例 4。
- 如果指定了
返回值
返回 VARCHAR 类型的值。
示例
-- Extract all characters starting from the first character "s".
MySQL > select substring("starrockscluster", 1);
+-------------------------------------+
| substring('starrockscluster', 1) |
+-------------------------------------+
| starrocks |
+-------------------------------------+
-- The position is negative and the counting is from the end of the string.
MySQL > select substring("starrocks", -5, 5);
+-------------------------------+
| substring('starrocks', -5, 5) |
+-------------------------------+
| rocks |
+-------------------------------+
-- The position exceeds the length of the string and an empty string is returned.
MySQL > select substring("apple", 8, 2);
+--------------------------------+
| substring('apple', 8, 2) |
+--------------------------------+
| |
+--------------------------------+
-- There are 5 matching characters. The length 9 exceeds the length of the matching characters and all the matching characters are returned.
MySQL > select substring("apple", 1, 9);
+--------------------------+
| substring('apple', 1, 9) |
+--------------------------+
| apple |
+--------------------------+
关键词
substring,string,sub