我有一列包含网址(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
我想把“更新”这个词改成“新闻”。可以用脚本做到这一点吗?
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/
是的,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....
updates
只在字符串中出现一次,那么这将起作用。否则,您将陷入直接的字符串操作,这在 MySQL 中是一个真正的痛苦。那时,编写一次性脚本来选择字段,在客户端进行操作,然后回写会更容易。
replace 函数应该适合您。
REPLACE(str,from_str,to_str)
返回字符串 str,其中所有出现的字符串 from_str 都替换为字符串 to_str。 REPLACE()
在搜索 from_str 时执行区分大小写的匹配。
您可以简单地使用 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;
除了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...
在我的示例中,字符串 articles/news/
存储在 other_table t2
中,无需在 WHERE
子句中使用 LIKE
。
REPLACE 功能非常方便搜索和替换表格中的文本,例如更新过时的 URL、纠正拼写错误等。
UPDATE tbl_name
SET
field_name = REPLACE(field_name,
string_to_find,
string_to_replace)
WHERE
conditions;
WHERE LIKE
子句,因为如果要查找的文本不存在,则不会更新该行,但是它应该加快速度。”LIKE '%%'
不使用任何索引,如果该 WHERE 中还有其他部分,例如像date_added > '2014-07-01'
之类的东西,它可能会有所帮助