2017-07-14 37 views
-1

我有一個蜂房表如下:從databsae柱更換多個串具有不同的替換

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

在此表中我需要替換字符串如「薩欽」與「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」。我的意思是它應該替換兩個字符串。

+0

提供足夠多的數據樣本以反映您想要應用的邏輯。也包括所需的結果(並且**不是**您當前正在獲得的結果) –

回答

0

可以嵌套內容替換:

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

你不需要正則表達式,所以只需使用replace()

+0

當id = 4時,我的名字是「sachin_sourav」,不應該改變。只有完整的單詞需要被替換。我試過嵌套regexp_replace,它工作。我可以不需要case..when聲明。 –

+0

「sachin」僅在字符串的開頭,並且總是會有一個空格跟隨?如果是這樣,用replace(s.name,'sachin','ST')替換內部的replace()來搜索和保存空間。 –