MySQL - 出现时替换字符串
MySQL - Replace string when it appears
'PrizeMoneyBreakDown' 列包含多个字符串,用分号分隔。我正在尝试从数据中删除字符串 'total value'、'trophy total value' 和 'welfare fund'。这些字符串有时只出现在数据中,所以它不像只删除最后三个字符串那么简单。我需要编写一个查询来删除它们出现的字符串 IF。
数据示例:
1st,5285;2nd,1680;3rd,885;4th,550;5th,350;6th,350;7th,350;8th,350;total_value,10000;welfare_fund,200;trophy_total_value,150;
期望的数据输出:
1st,5285;2nd,1680;3rd,885;4th,550;5th,350;6th,350;7th,350;8th,350
当前代码(仅删除单词 'total value' 等 - 不删除与字符串关联的奖金):
SELECT PrizeMoneyBreakDown,
REPLACE(REPLACE(REPLACE(PrizeMoneyBreakDown,'total_value',""),'welfare_fund',""),'trophy_total_value',"") as new
FROM race2;
在 MySQL 8+ 上,我们可以使用 REGEXP_REPLACE
:
SELECT PrizeMoneyBreakDown,
REGEXP_REPLACE(PrizeMoneyBreakDown,
'(total_value|welfare_fund|trophy_total_value),\d+;',
'') AS NewPrizeMoneyBreakDown
FROM race2;
如果你想更新实际的列然后使用:
UPDATE race2
SET PrizeMoneyBreakDown = REGEXP_REPLACE(
PrizeMoneyBreakDown,
'(total_value|welfare_fund|trophy_total_value),\d+;',
'')
WHERE PrizeMoneyBreakDown REGEXP '(total_value|welfare_fund|trophy_total_value),\d+;';
'PrizeMoneyBreakDown' 列包含多个字符串,用分号分隔。我正在尝试从数据中删除字符串 'total value'、'trophy total value' 和 'welfare fund'。这些字符串有时只出现在数据中,所以它不像只删除最后三个字符串那么简单。我需要编写一个查询来删除它们出现的字符串 IF。
数据示例:
1st,5285;2nd,1680;3rd,885;4th,550;5th,350;6th,350;7th,350;8th,350;total_value,10000;welfare_fund,200;trophy_total_value,150;
期望的数据输出:
1st,5285;2nd,1680;3rd,885;4th,550;5th,350;6th,350;7th,350;8th,350
当前代码(仅删除单词 'total value' 等 - 不删除与字符串关联的奖金):
SELECT PrizeMoneyBreakDown,
REPLACE(REPLACE(REPLACE(PrizeMoneyBreakDown,'total_value',""),'welfare_fund',""),'trophy_total_value',"") as new
FROM race2;
在 MySQL 8+ 上,我们可以使用 REGEXP_REPLACE
:
SELECT PrizeMoneyBreakDown,
REGEXP_REPLACE(PrizeMoneyBreakDown,
'(total_value|welfare_fund|trophy_total_value),\d+;',
'') AS NewPrizeMoneyBreakDown
FROM race2;
如果你想更新实际的列然后使用:
UPDATE race2
SET PrizeMoneyBreakDown = REGEXP_REPLACE(
PrizeMoneyBreakDown,
'(total_value|welfare_fund|trophy_total_value),\d+;',
'')
WHERE PrizeMoneyBreakDown REGEXP '(total_value|welfare_fund|trophy_total_value),\d+;';