更新列值,替换部分字符串

Add*_*dev 302 mysql sql

我在MySQL数据库中有一个包含以下列的表

[id, url]
Run Code Online (Sandbox Code Playgroud)

网址如下:

 http://domain1.com/images/img1.jpg
Run Code Online (Sandbox Code Playgroud)

我想将所有网址更新到另一个域

 http://domain2.com/otherfolder/img1.jpg
Run Code Online (Sandbox Code Playgroud)

保持文件的名称不变.

我必须运行什么查询?

Dmy*_*nko 641

UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')
Run Code Online (Sandbox Code Playgroud)

  • REPLACE也适用于SELECT,非常有用:) (4认同)
  • 非常有用,非常快速地处理2000次查询而失败. (2认同)
  • 观看 CaSiNg(问我怎么知道!)。:) (2认同)

Mar*_*c B 153

UPDATE yourtable
SET url = REPLACE(url, 'http://domain1.com/images/', 'http://domain2.com/otherfolder/')
WHERE url LIKE ('http://domain1.com/images/%');
Run Code Online (Sandbox Code Playgroud)

相关文档:http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace

  • 你好 - 为什么我需要在哪里? (13认同)
  • @GuyCohen因为否则查询将修改表中的每一行.`WHERE`子句优化查询以仅修改具有特定URL的行.从逻辑上讲,结果将是相同的,但添加"WHERE"将使操作更快. (13认同)
  • `WHERE`还确保你只用`http:// etc/etc /`或`string_to_be_replaced'替换_begin_的部分字符串.例如,在给定的答案中,`http://domain1.com/ images/this/is/a/test`会受到影响,但`foobar/http:// domain1.com/images /`不会. (3认同)

sch*_*ack 26

尝试使用REPLACE功能:

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

请注意,它区分大小写.

  • @UniversalGrasp在这里看到很多可能的答案:http://stackoverflow.com/questions/5656056/case-insensitive-replace-in-mysql (2认同)

小智 9

您需要WHERE子句来替换符合WHERE子句中的条件的记录(而不是所有记录).您使用%符号表示部分字符串:IE

LIKE('... // domain1.com/images/%'); 意味着所有记录BEGIN以"... // domain1.com/images/"和有什么AFTER(这是针对%...)

另一个例子:

LIKE('%http://domain1.com/images/% ')表示在字符串的任何部分包含" http://domain1.com/images/ "的所有记录......


小智 9

尝试这个...

update [table_name] set [field_name] = 
replace([field_name],'[string_to_find]','[string_to_replace]');
Run Code Online (Sandbox Code Playgroud)