起始位置:我有一个 SQL-DB,其中包含几个带有数百或数千个条目的表。现在,在几个字段(列)中存在 URL,应将其缩短(为原始 URL 的摘录)并添加新参数。问题是,有一些“查找和替换”要做:
查找所有表的所有字段/列中的所有(旧)URL(独立或中间文本)...
http://www.domain.com/click?p(abcdef)a(123456)url(http://www.url.com)
...并将旧 URL 替换为(新)URL:
...如您所见,我需要在 url 参数内使用通配符...例如 http://www.domain.com/click?p(abcdef)a(123456)url(*)
因为旧网址以 )
结尾,我只需要旧网址(第二个网址)的摘录以及新的网址参数。
- 旧网址中 ( 和 ) 内的网址可能会有所不同……可能有数百或数千个不同的网址。
- 网址位于多个表格的多个字段中……内部且大部分被文本包围,不一定是独立的(见下表)。
- 每个条目可能有多个 个字段/列,而每个字段/列没有、一个或多个 需要更改的 URL。
表示例:
+----------+---+-------------------+---------------+---+--------------+--------------+
| entry_id | … | field_id_1 | field_ft_1 | … | field_id_199 | field_ft_199 |
+----------+---+-------------------+---------------+---+--------------+--------------+
| 21364 | … | blabla URL blabla | NULL | … | none | none |
| 21363 | … | text URL text | text URL text | … | none | URL |
| … | … | text URL text URL | NULL | … | URL text | none |
+----------+---+-------------------+---------------+---+--------------+--------------+
字段/列值示例:
The new «App of the Week» is named «<a href="http://www.domain.com/click?p(abcdef)a(123456)url(https://itunes.apple.com/ch/app/popagraph/id587595362?mt=8)">PopAGraph</a>».
This App does this and that and bla bla bla <a href="http://www.domain.com/click?p(abcdef)a(123456)url(https://itunes.apple.com/ch/app/popagraph/id587595362?mt=8)">kostenlos</a>.
In the iOS Store there are «Editors Choise» like: «<a href="http://www.domain.com/click?p(abcdef)a(123456)url(https://itunes.apple.com/ch/app/the-room-two/id667362389?mt=8)">The Room Two</a>» (CHF 3.00). And some more Text bla bla bla.
更新:由于缺乏细节而重写了整个问题
最佳答案
要查找旧字符串的最后一个 URL
部分,请使用 substring_index
和 substr
函数。
示例:
SET @old_value :=
'http://www.domain.com/click?p(abcdef)a(123456)url(http://www.url.com)';
select @url := substr( @u := substring_index( @old_value, '(', -1 )
from 1
for ( length( @u ) - 1 )
) as url
这将返回
+--------------------+
| url |
+--------------------+
| http://www.url.com |
+--------------------+
要使用新的 url
值更新记录,您必须使用 concat
将查询参数附加到 URL。
示例:
update my_table
set url_col = concat( @url, '/?at=uvwxyz' )
where
url_col = @old_value
-- and -- add more conditions if required
-- ... ...
引用:
- MySQL: SUBSTRING_INDEX( str, delim, count )
- 返回字符串 str 中出现 count 次之前的子字符串 定界符delim。如果 count 为正,则左侧的所有内容 返回最终分隔符(从左侧算起)。如果计数是 负数,最后分隔符右侧的所有内容(计数 从右)返回。 SUBSTRING_INDEX() 执行 搜索 delim 时区分大小写。
关于mysql - SQL 查找并用通配符替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22293722/