首页 > 解决方案 > 如何根据 SQL 模式更新列内的特定数据?

问题描述

由于某些原因,在我的数据库中,在表列中,我有一些带有绝对 url 的数据,如下所示:

+---------------------------------+
|               url               |
+---------------------------------+
| /foo/12                         |
| http://www.myexample.com/foo/13 |
| http://www.myexample.com/foo/14 |
+---------------------------------+

我想像这样将绝对 url 更新为相对 url:

+---------------------------------+
|               url               |
+---------------------------------+
| /foo/12                         |
| /foo/13                         |
| /foo/14                         |
+---------------------------------+

如何使用 SQL 查询来做到这一点?

标签: mysqlsqlsql-updatepattern-matching

解决方案


您可以使用REPLACE(str,from_str,to_str)

返回字符串 str,其中所有出现的字符串 from_str 都替换为字符串 to_str。REPLACE() 在搜索 from_str 时执行区分大小写的匹配。

所以你可以在更新查询中写 replace(url,' http://www.myexample.com ','')

update table_name set url = replace(url,'http://www.myexample.com','') where 1=1

推荐阅读