如何使用 mySQL replace() 替换多条记录中的字符串? [英] How can I use mySQL replace() to replace strings in multiple records?

查看:88
本文介绍了如何使用 mySQL replace() 替换多条记录中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个数据库,其中有一堆记录,其中一列中有一些错误数据,其中嵌入式编辑器转义了一些不应该转义的内容,并且破坏了生成的链接.

We have a database that has a bunch of records with some bad data in one column, in which an embedded editor escaped some stuff that shouldn't have been escaped and it's breaking generated links.

我想运行一个查询来替换所有记录中的坏字符,但不知道该怎么做.我找到了 replace()函数在 MySQL 中,但如何在查询中使用它?

I want to run a query to replace the bad characters in all the records, but can't figure out how to do it. I found the replace() function in MySQL, but how can I use it inside a query?

例如,如果我想用实际的小于尖括号 (<) 替换字符串 &lt;articleItem 列中具有 &lt; 的所有记录?它可以在单个查询中完成(即一次性选择和替换所有内容),还是我必须执行多个查询?即使是多个查询,我如何使用 replace() 对多个记录上的字段值进行替换?

For example, what would be the correct syntax if I wanted to replace the string &lt; with an actual less-than angle bracket (<) in all records that have &lt; in the articleItem column? Can it be done in a single query (i.e. select and replace all in one swoop), or do I have to do multiple queries? Even if it's multiple queries, how do I use replace() to do the replace on the value of a field on more than one record?

推荐答案

在非常通用的层面

UPDATE MyTable

SET StringColumn = REPLACE (StringColumn, 'SearchForThis', 'ReplaceWithThis')

WHERE SomeOtherColumn LIKE '%PATTERN%'

在您的情况下,您说这些已转义,但由于您没有指定它们是如何转义的,因此假设它们已转义为 GREATERTHAN

In your case you say these were escaped but since you don't specify how they were escaped, let's say they were escaped to GREATERTHAN

UPDATE MyTable

SET StringColumn = REPLACE (StringColumn, 'GREATERTHAN', '>')

WHERE articleItem LIKE '%GREATERTHAN%'

由于您的查询实际上将在字符串内工作,因此您的 WHERE 子句进行模式匹配不太可能提高任何性能 - 它实际上会为服务器生成更多工作.除非您有另一个 WHERE 子句成员可以使此查询执行得更好,否则您可以简单地进行如下更新:

Since your query is actually going to be working inside the string, your WHERE clause doing its pattern matching is unlikely to improve any performance - it is actually going to generate more work for the server. Unless you have another WHERE clause member that is going to make this query perform better, you can simply do an update like this:

UPDATE MyTable
SET StringColumn = REPLACE (StringColumn, 'GREATERTHAN', '>')

你也可以嵌套多个REPLACE调用

UPDATE MyTable
SET StringColumn = REPLACE (REPLACE (StringColumn, 'GREATERTHAN', '>'), 'LESSTHAN', '<')

您也可以在选择数据时执行此操作(而不是在保存数据时).

You can also do this when you select the data (as opposed to when you save it).

所以而不是:

从 MyTable 中选择 MyURLString

你可以这样做

SELECT REPLACE (MyURLString, 'GREATERTHAN', '>') as MyURLString From MyTable

这篇关于如何使用 mySQL replace() 替换多条记录中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆