Mysql替换字段中指定字符(replace 函数)

一、简介

函数将字符串中出现的所有子字符串替换为新的子字符串。 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%';

 

posted @ 2024-05-09 11:17  zhangzhiping35  阅读(182)  评论(0编辑  收藏  举报