简体   繁体   中英

Update(populate) SQL Table column with data from another database table

I have two databases, test1 and test2 . test1 has the following table1 .

ID | Word      | Def
1.   abandon     NULL
2.   test        NULL

And for test2 database, I have the following table2 .

ID | Word      | Def
1.   abandon     (verb) the meaning of abandon
2.   word2       the meaning of word2
3.   abandon     (noun) the meaning of abandon

I want to copy the definitions of words from the database test2 , table2 to database test1 , table1 where a word from table1 matches with the same word from table2 and avoid duplicate word; for example, the word abandon appears twice in table2 and only once in table1 . If possible, I want to append the second definition of the word abandon appended to the first definition and update it in table1 , Def column.

I have tried the following.

UPDATE test1.table1 
SET Def = (SELECT Def 
           FROM test2.table2 
           WHERE test1.table1.Word = test2.table2.Word);

But I am getting an error which I do not quite understand.

You need to get only one definition. Here is an approach that works in MySQL and Postgres:

UPDATE test1.table1 t1
    SET Def = (SELECT Def
               FROM test2.table2 t2
               WHERE t1.Word = t2.Word
               ORDER BY id
               LIMIT 1);

The LIMIT 1 might alternatively be select top 1 or fetch first 1 row only .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM