Home > Net >  MYSQL Replace string that contains specific substring
MYSQL Replace string that contains specific substring

Time:10-12

Basically, I want to substring all strings that contain the word COMPRIMIDO to keep only COMPRIMIDO

Example:

medication_title medication_type medication_result
ZYTIGA 500 MG COMPRIMIDO REVESTIDO COMPRIMIDO
VERZENIOS 50 MG COMPRIMIDO MOLE COMPRIMIDO

I tried using replace function:

REPLACE(REPLACE(medication_type, 'COMPRIMIDO REVESTIDO', 'COMPRIMIDO'), 'COMPRIMIDO MOLE', 'COMPRIMIDO') as medication_result

But I think there are easier ways to do this, especially thinking about situations where we can have several string variations with "COMPRIMIDO"

Ideas?

CodePudding user response:

Easier to use a case expression with LIKE.

select medication_title, medication_type, 
 case 
  when upper(medication_type) like '%COMPRIMIDO%' then 'COMPRIMIDO' 
  else medication_type 
 end medication_result
from my_data
  • Related