一、简介
函数将字符串中出现的所有子字符串替换为新的子字符串。
REPLACE()
函数是基于字符的替换,并且替换字符串时是区分大小写的。
二、语法
这里是 MySQL
REPLACE()
函数的语法:
REPLACE(str, from_str, to_str)
参数
str
必需的。 原字符串。
from_str
必需的。 被替换的子字符串。
to_str
必需的。 用来替换的新子字符串。
返回值
REPLACE(str, from_str, to_str)
函数返回
str
中的所有
from_str
被
to_str
替换后的字符串。
- 当任意一个参数为
NULL
时,REPLACE()
函数将返回NULL
。
三、实例
(1)查询
这里列出了几个常见的
REPLACE()
示例。
SELECT
REPLACE('Hello World', 'World', 'Alice'),
REPLACE('Hello World', 'l', 'L'),
REPLACE('Hello World', 'h', 'HH')\G
*************************** 1. row ***************************
REPLACE('Hello World', 'World', 'Alice'): Hello Alice
REPLACE('Hello World', 'l', 'L'): HeLLo WorLd
REPLACE('Hello World', 'h', 'HH'): Hello World
注意: 由于
REPLACE
执行的是区分大小写的搜索,因此
REPLACE('Hello World', 'h', 'HH')
不会发生任何替换。
(2)更新
UPDATE table_name
SET field_name
= REPLACE (
field_name
,
'from_str',
'to_str'
)
WHERE
field_name
LIKE '%from_str%';
该语句可直接将字段field_name中的from_str值更新为to_str。
版权归原作者 zhanglf1016 所有, 如有侵权,请联系我们删除。