使用不同的替换项替换数据库列中的多个字符串

Replacing multiple strings from a databsae column with distinct replacements

我有一个蜂巢 table 如下:

+----+---------------+-------------+
| id | name          | partnership |
+----+---------------+-------------+
| 1  | sachin sourav | first       |
| 2  | sachin sehwag | first       |
| 3  | sourav sehwag | first       |
| 4  | sachin_sourav | first       |
+----+---------------+-------------+

在这个 table 中,我需要将 "sachin" 等字符串替换为 "ST",将 "Sourav" 替换为 "SG"。我正在使用以下查询,但没有解决问题。

查询:

select 
    *,
    case
       when name regexp('\bsachin\b') 
          then regexp_replace(name,'sachin','ST')
       when name regexp('\bsourav\b') 
          then regexp_replace(name,'sourav','SG')
       else name
    end as newName
from sample1;

结果:

+----+---------------+-------------+---------------+
| id | name          | partnership | newname       |
+----+---------------+-------------+---------------+
| 4  | sachin_sourav | first       | sachin_sourav |
| 3  | sourav sehwag | first       | SG sehwag     |
| 2  | sachin sehwag | first       | ST sehwag     |
| 1  | sachin sourav | first       | ST sourav     |
+----+---------------+-------------+---------------+

问题:我的意图是,当 id = 1 时,newName 列的值应为 "ST SG"。我的意思是它应该替换两个字符串。

您可以嵌套替换:

select s.*,                                             
       replace(replace(s.name, 'sachin', 'ST'), 'sourav', 'SG') as newName
from sample1 s;

您不需要正则表达式,所以只需使用 replace().