MySQL 在 X 个字符后更新部分记录
MySQL updating part of the record after X many characters
假设我有一条像 https://whosebug.com//questions/
这样的记录,不知何故发生了这种情况,我想将记录更新为 https://whosebug.com/questions/
。
到目前为止,我想替换每个出现的 //
,但这也会破坏 https://
部分,因为 http:/
。
我已经通过以下方式确定了所有损坏的记录:
SELECT TRIM(TRAILING SUBSTRING_INDEX(url, '//', -1) FROM url) FROM table_name WHERE length(TRIM(TRAILING SUBSTRING_INDEX(url, '//', -1) FROM url)) > 8;
这会在 8 个字符之后进行检查,因此会跳过所有出现的 http://
和 https://
。目前有 302 个 URL 处于这种情况。
我该如何解决这个问题?
检查这个:
SET @val = 'https://whosebug.com//questions/';
select
concat(
substr(@val, 1, instr(@val, '//') + 1),
replace(substr(@val, instr(@val, '//') + 2),'//', '/')
)
它将第一个之后出现的所有 //
替换为 /
见 demo
所以你可以在更新中使用它:
update tablename
set mycolumn = concat(
substr(mycolumn, 1, instr(mycolumn, '//') + 1),
replace(substr(mycolumn, instr(mycolumn, '//') + 2),'//', '/')
)
替换两次。
那么问题是 https://
也会变成 https:/
吗?
只是意味着您需要再次添加 1 个丢失的斜线。
UPDATE yourtable
SET url = REPLACE(REPLACE(url,'//','/'),':/','://')
WHERE url LIKE '%://%//%'
假设我有一条像 https://whosebug.com//questions/
这样的记录,不知何故发生了这种情况,我想将记录更新为 https://whosebug.com/questions/
。
到目前为止,我想替换每个出现的 //
,但这也会破坏 https://
部分,因为 http:/
。
我已经通过以下方式确定了所有损坏的记录:
SELECT TRIM(TRAILING SUBSTRING_INDEX(url, '//', -1) FROM url) FROM table_name WHERE length(TRIM(TRAILING SUBSTRING_INDEX(url, '//', -1) FROM url)) > 8;
这会在 8 个字符之后进行检查,因此会跳过所有出现的 http://
和 https://
。目前有 302 个 URL 处于这种情况。
我该如何解决这个问题?
检查这个:
SET @val = 'https://whosebug.com//questions/';
select
concat(
substr(@val, 1, instr(@val, '//') + 1),
replace(substr(@val, instr(@val, '//') + 2),'//', '/')
)
它将第一个之后出现的所有 //
替换为 /
见 demo
所以你可以在更新中使用它:
update tablename
set mycolumn = concat(
substr(mycolumn, 1, instr(mycolumn, '//') + 1),
replace(substr(mycolumn, instr(mycolumn, '//') + 2),'//', '/')
)
替换两次。
那么问题是 https://
也会变成 https:/
吗?
只是意味着您需要再次添加 1 个丢失的斜线。
UPDATE yourtable
SET url = REPLACE(REPLACE(url,'//','/'),':/','://')
WHERE url LIKE '%://%//%'