MySql - 更新字符串部分的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1876762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySql - Way to update portion of a string?
提问by n00b0101
I'm looking for a way to update just a portion of a string via MySQL query.
我正在寻找一种方法来通过 MySQL 查询更新字符串的一部分。
For example, if I have 10 records all containing 'string' as part of the field value (i.e., 'something/string', 'something/stringlookhere', 'something/string/etcetera', is there a way to change 'string' to 'anothervalue' for each row via one query, so that the result is 'something/anothervalue', 'something/anothervaluelookhere', 'something/string/etcetera', is there a way to change 'anothervalue'
例如,如果我有 10 条记录都包含“字符串”作为字段值的一部分(即,“某事/字符串”、“某事/字符串看这里”、“某事/字符串/等等”,有没有办法更改“字符串” ' 通过一个查询将每一行的“另一个值”改为“另一个值”,因此结果是“某物/另一个值”、“某物/另一个值看这里”、“某物/字符串/等等”,有没有办法更改“另一个值”
回答by Kaleb Brasee
I think this should work:
我认为这应该有效:
UPDATE table
SET field = REPLACE(field, 'string', 'anothervalue')
WHERE field LIKE '%string%';
回答by Tatu Ulmanen
UPDATE `table` SET `field` = REPLACE(`field`, 'string', 'anothervalue')
回答by Bernard Chen
Use the LIKE
operator to find the rows that you care about and update them using the REPLACE
function.
使用LIKE
运算符查找您关心的行并使用该REPLACE
函数更新它们。
For example:
例如:
UPDATE table_name SET field_name = REPLACE(field_name,'search','replace') WHERE field_name LIKE '%some_value%'