MySQL字符串替换

我有一个列包含url (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

我想把“更新”这个词改成“新闻”。是否可以通过脚本来实现这一点?

794684 次浏览

取代函数应该可以为您工作。

REPLACE(str,from_str,to_str)

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

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

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

< a href = " http://dev.mysql.com/doc/refman/5.0/en/string-functions.html function_replace " > http://dev.mysql.com/doc/refman/5.0/en/string-functions.html function_replace < / >

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

SELECT REPLACE(string_column, 'search', 'replace') as url....
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'

现在这些行就像

# EYZ0

# EYZ0

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

如果你需要根据另一列动态地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

您可以简单地使用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;

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

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