Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and replace from another table mysql

I need to find and replace multiplie strings from table "phrases" using table "dict"

I have code like:

update  phrases, dict
set     phrases.name = replace(phrases.name, dict.source, dict.translate)
where   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    | good
3  | lenova | lenovo
4  | blck   | black
5  | comput | computer
6  | nb     | notebook

I need get to phares like this:

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

It will replace only 1 string at once in row, but I have about 3-10 strings to replace.

How this code can be changed to replace all strings in rows?

like image 711
user2421781 Avatar asked Sep 22 '14 09:09

user2421781


1 Answers

Create function and use it for update

CREATE OR REPLACE FUNCTION translate_phrases_name(phraseId numeric)
  RETURNS character varying AS
$BODY$
DECLARE
phrasesString character varying;
newPhrasesString character varying;
currentWord character varying;
currentWordTranslation character varying;
i numeric;
wordsCount numeric;


BEGIN

phrasesString := (select name from phrases where id = phraseId);
--the string that u want to get, we will use it later
newPhrasesString := phrasesString;

phrasesString := trim(phrasesString);

phrasesString := regexp_replace(phrasesString, '\s+', ' ', 'g');

wordsCount := length(regexp_replace(phrasesString, '[^ ]+', '', 'g'));
--the count of the words is +1 more than count of spaces
wordsCount := wordsCount + 1;


--working with each word 
for i in 1..wordsCount loop
    --find first word in string
    currentWord := substring(phrasesString from '\A[^ ]+');
    --find translation in dict table
    currentWordTranslation := (select translate from dict where source = currentWord);
    --constructing string that u want
    newPhrasesString := replace(newPhrasesString, currentWord, currentWordTranslation);
    --kill first word for 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 TO postgres;

the final update will be:

update phrases
    set name = (select translate_phrases_name(id));
like image 85
Ruslan Babich Avatar answered Sep 22 '22 03:09

Ruslan Babich