translate
替换字符串中指定的字符。 它通过获取一个字符串 (source
) 作为输入,并将 source
中 from_string
的字符替换为 to_string
。
该函数从 v3.2 版本开始支持。
语法
TRANSLATE(source, from_string, to_string)
参数
-
source
:支持VARCHAR
类型。 要转换的源字符串。 如果source
中的字符在from_string
中找不到,则它将直接包含在结果字符串中。 -
from_string
:支持VARCHAR
类型。from_string
中的每个字符要么被to_string
中对应的字符替换,要么如果没有对应的字符(即如果to_string
的字符少于from_string
),则该字符将从结果字符串中排除。 请参见示例 2 和 3。如果一个字符在from_string
中出现多次,则只有第一次出现有效。 请参见示例 5。 -
to_string
:支持VARCHAR
类型。 用于替换字符的字符串。 如果在to_string
中指定的字符多于from_string
参数,则to_string
中的额外字符将被忽略。 请参见示例 4。
返回值
返回 VARCHAR
类型的值。
结果为 NULL
的情况
-
任何输入参数为
NULL
。 -
转换后结果字符串的长度超过
VARCHAR
的最大长度 (1048576)。
示例
-- Replace 'ab' in the source string with '12'.
mysql > select translate('abcabc', 'ab', '12') as test;
+--------+
| test |
+--------+
| 12c12c |
+--------+
-- Replace 'mf1' in the source string with 'to'. 'to' has less characters than 'mf1' and '1' is excluded from the result string.
mysql > select translate('s1m1a1rrfcks','mf1','to') as test;
+-----------+
| test |
+-----------+
| starrocks |
+-----------+
-- Replace 'ab' in the source string with '1'. '1' has less characters than 'ab' and 'b' is excluded from the result string.
mysql > select translate('abcabc', 'ab', '1') as test;
+------+
| test |
+------+
| 1c1c |
+------+
-- Replace 'ab' in the source string with '123'. '123' has more characters than 'ab' and '3' is ignored.
mysql > select translate('abcabc', 'ab', '123') as test;
+--------+
| test |
+--------+
| 12c12c |
+--------+
-- Replace 'aba' in the source string with '123'. 'a' appears twice and only the first occurrence of 'a' is replaced.
mysql > select translate('abcabc', 'aba', '123') as test;
+--------+
| test |
+--------+
| 12c12c |
+--------+
-- Use this function with repeat() and concat(). The result string exceeds the maximum length of VARCHAR and NULL is returned.
mysql > select translate(concat('bcde', repeat('a', 1024*1024-3)), 'a', 'z') as test;
+--------+
| test |
+--------+
| NULL |
+--------+
-- Use this function with length(), repeat(), and concat() to calculate the length of the result string.
mysql > select length(translate(concat('bcd', repeat('a', 1024*1024-3)), 'a', 'z')) as test;
+---------+
| test |
+---------+
| 1048576 |
+---------+