sql - find and replace from another table mysql -


i need find , replace multiplie strings table "phrases" using table "dict"

i have code like:

update  phrases, dict set     phrases.name = replace(phrases.name, dict.source, dict.translate)   phrases.name <> replace(phrases.name, dict.source, dict.translate) 

pharses table example:

id | name | .. | .. 1  | macbook wht comput | .. 2  | lenova blck god nb | .. 

dict table example:

id | source | translate  1  | wht    | white 2  | god    | 3  | lenova | lenovo 4  | blck   | black 5  | comput | computer 6  | nb     | notebook 

i need phares this:

id | name | .. | .. 1  | macbook white computer | .. 2  | lenova black notebook | .. 

it replace 1 string @ once in row, have 3-10 strings replace.

how code can changed replace strings in rows?

create function , use update

create or replace function translate_phrases_name(phraseid numeric)   returns character varying $body$ declare phrasesstring character varying; newphrasesstring character varying; currentword character varying; currentwordtranslation character varying; numeric; wordscount numeric;   begin  phrasesstring := (select name phrases id = phraseid); --the string u want get, use later newphrasesstring := phrasesstring;  phrasesstring := trim(phrasesstring);  phrasesstring := regexp_replace(phrasesstring, '\s+', ' ', 'g');  wordscount := length(regexp_replace(phrasesstring, '[^ ]+', '', 'g')); --the count of words +1 more count of spaces wordscount := wordscount + 1;   --working each word  in 1..wordscount loop     --find first word in string     currentword := substring(phrasesstring '\a[^ ]+');     --find translation in dict table     currentwordtranslation := (select translate dict source = currentword);     --constructing string u want     newphrasesstring := replace(newphrasesstring, currentword, currentwordtranslation);     --kill first word next iteration of loop     phrasesstring := replace(phrasesstring, currentword, ''); end loop;  return newphrasesstring;  end; $body$   language plpgsql volatile   cost 100; alter function translate_phrases_name(numeric)   owner postgres; 

the final update be:

update phrases     set name = (select translate_phrases_name(id)); 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -