MySQL字符串替换

n00*_*00b 542 mysql replace

我有一个包含urls(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
Run Code Online (Sandbox Code Playgroud)

我想将"更新"改为"新闻".是否可以使用脚本执行此操作?

Gir*_*ldi 1259

UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Run Code Online (Sandbox Code Playgroud)

现在的行就像

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

将会

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

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

  • @JohnCrawford根据链接中的文章:"你不一定要在最后添加`WHERE LIKE`子句,因为如果要查找的文本不存在,那么行将不会更新,**但是它应该加快速度**." (53认同)
  • 快速问题,是否真的需要"WHERE"条款? (22认同)
  • 我相信在这种情况下,WHERE没用,因为`LIKE'%%'`不使用任何索引,如果WHERE中有其他部分,例如`date_added>'2014-07-01'`它可能有帮助 (11认同)
  • 当我需要在mysql中替换某些内容时,我总是来这里参考 (11认同)
  • WHERE子句使您可以特定地控制要替换的内容.如果找不到匹配项,则不会检查每一行,并且可能会替换数据. (3认同)
  • 由于这个原因,WHERE非常有用:只需要写入需要写入的行.如果没有WHERE,即使某些行中的值不会发生变化,也会写入所有行.如果您的表很大,或者您有触发器,WHERE将避免大量不必要的处理. (3认同)

ont*_*ia_ 140

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

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
    -> 'WwWwWw.mysql.com'
Run Code Online (Sandbox Code Playgroud)

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

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

SELECT REPLACE(string_column, 'search', 'replace') as url....
Run Code Online (Sandbox Code Playgroud)


Jay*_*Jay 20

替代函数应该为你工作.

REPLACE(str,from_str,to_str)
Run Code Online (Sandbox Code Playgroud)

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


Dee*_*har 8

你可以简单地使用replace()函数,

与where子句 -

update tabelName set columnName=REPLACE(columnName,'from','to') where condition;
Run Code Online (Sandbox Code Playgroud)

没有where子句 -

update tabelName set columnName=REPLACE(columnName,'from','to');
Run Code Online (Sandbox Code Playgroud)

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

select REPLACE(columnName,'from','to') as updateRecord;
Run Code Online (Sandbox Code Playgroud)


Raf*_*shi 6

除了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...
Run Code Online (Sandbox Code Playgroud)

在我的示例中,字符串articles/news/存储在其中,other_table t2并且不需要LIKEWHERE子句中使用.