我有一个包含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/
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时执行区分大小写的匹配.
你可以简单地使用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)
除了gmaggio的答案,如果您需要动态,REPLACE并UPDATE根据另一列,您可以做例如:
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并且不需要LIKE在WHERE子句中使用.