Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Updating rows based on reference data in lookup table

Tags:

sql

sql-server

I have a table, tbl_english, containing the column "word". I also have a table, tbl_translation, containing the columns "german_word" and "english_word".

tbl_translation is supposed to be a lookup table to see if there are any german words in tbl_english' column "word"

So what I want to do is;

For each tbl_english.word, iterate through tbl_translation.german_word and look for matching value. If match exists, update tbl_english.word with the value in tbl_translation.english_word from current row in tbl_translation

The intention is to replace any rogue german words existing in tbl_english with their correct translation from the lookup table tbl_translation

So far what I have come up with is this;

UPDATE tbl_english SET word = 
    (SELECT english_word FROM tbl_translation 
        WHERE tbl_english.word = german_word) 
    WHERE word IN
        (SELECT german_word FROM tbl_translation
            WHERE tbl_english.word = german_word )

However, this fails when there are multiple instances of the same or different words resulting from the first sub-select. Is there a simple way to solve the problem?

Example:

tbl_english contains; Mädchen Frau Boy Giraffe Baum

tbl_translation contains (german, english); Mädchen, Female Frau, Female

So in tbl_english I would like to see the following result; Female Female Boy Giraffe Baum

Edit: Not every word in tbl_english will have a reference row in the translation table. Edit2: Added example

like image 585
cc0 Avatar asked Feb 21 '23 07:02

cc0


1 Answers

UPDATE e
  SET word = t.english_word
  FROM dbo.tbl_english AS e
  INNER JOIN dbo.tbl_translation AS t
  ON e.word = t.german_word
  WHERE e.word <> t.english_word;
like image 86
Aaron Bertrand Avatar answered Feb 24 '23 06:02

Aaron Bertrand