ChatGPT解决这个技术问题 Extra ChatGPT

MySQL字符串替换

我有一列包含网址(id,url):

http://www.example.com/articles/updates/43
http://www.example.com/articles/updates/866
http://www.example.com/articles/updates/323
http://www.example.com/articles/updates/seo-url
http://www.example.com/articles/updates/4?something=test

我想把“更新”这个词改成“新闻”。可以用脚本做到这一点吗?

我多年来一直来这里寻找 REPLACE(...) 参数的顺序。如果这个问题被删除,我将无法再做我的工作。谢谢!

r
rogerdpack
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'

现在的行就像

http://www.example.com/articles/updates/43

将会

http://www.example.com/articles/news/43

http://www.electrictoolbox.com/mysql-find-replace-text/


快速提问,真的需要“WHERE”子句吗?
@JohnCrawford 根据链接中的文章:“您不一定要在末尾添加 WHERE LIKE 子句,因为如果要查找的文本不存在,则不会更新该行,但是它应该加快速度。”
WHERE 子句使您可以特定控制要替换的内容。如果没有,将检查每一行,如果找到匹配项,则可能会替换数据。
我相信在这种情况下 WHERE 是无用的,因为 LIKE '%%' 不使用任何索引,如果该 WHERE 中还有其他部分,例如像 date_added > '2014-07-01' 之类的东西,它可能会有所帮助
当我需要替换mysql中的某些东西时,我总是来这里参考
o
onteria_

是的,MySQL 有一个 REPLACE() 函数:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
    -> 'WwWwWw.mysql.com'

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

请注意,如果您在使用 SELECT 时将其设为别名,会更容易

SELECT REPLACE(string_column, 'search', 'replace') as url....

只要 OP 的 updates 只在字符串中出现一次,那么这将起作用。否则,您将陷入直接的字符串操作,这在 MySQL 中是一个真正的痛苦。那时,编写一次性脚本来选择字段,在客户端进行操作,然后回写会更容易。
N
Nicholas Shanks

replace 函数应该适合您。

REPLACE(str,from_str,to_str)

返回字符串 str,其中所有出现的字符串 from_str 都替换为字符串 to_str。 REPLACE() 在搜索 from_str 时执行区分大小写的匹配。


S
Shiwangini

您可以简单地使用 replace() 函数。

例子:

带有where子句-

update tableName set columnName=REPLACE(columnName,'from','to') where condition;

没有where子句-

update tableName set columnName=REPLACE(columnName,'from','to');

注意:上面的查询如果直接在表中更新记录,如果你想在选择查询并且不应该影响表中的数据那么可以使用以下查询 -

select REPLACE(columnName,'from','to') as updateRecord;

R
RafaSashi

除了gmaggio的回答如果您需要根据另一列动态REPLACEUPDATE您可以这样做例如:

UPDATE your_table t1
INNER JOIN other_table t2
ON t1.field_id = t2.field_id
SET t1.your_field = IF(LOCATE('articles/updates/', t1.your_field) > 0, 
REPLACE(t1.your_field, 'articles/updates/', t2.new_folder), t1.your_field) 
WHERE...

在我的示例中,字符串 articles/news/ 存储在 other_table t2 中,无需在 WHERE 子句中使用 LIKE


G
Ganesh Giri

REPLACE 功能非常方便搜索和替换表格中的文本,例如更新过时的 URL、纠正拼写错误等。

  UPDATE tbl_name 
    SET 
        field_name = REPLACE(field_name,
            string_to_find,
            string_to_replace)
    WHERE
        conditions;