Search code examples
mysqlsqlsql-updatetoadsql-function

How to update one table based on the data of an other table?


I have the following 2 tables in mySQL. I would like to update table_1 with the data of table_2 if that data is not present in table_1 or if the data has changed.

These are my tables:

table_1:

id    name    desc     price 
------------------------------
1     a       audi        100
2     b       bmw         221
3     c       mercedes    331 

table_2:

id    name    desc      price
------------------------------
1     a       audi         1200
2     b       bmw          250
3     c       mercedes     500
4     d       opel         400
5     e       volkswagen   340

My desired output would be:

table_1

id    name    desc      price
------------------------------
1     a       audi         1200
2     b       bmw          250
3     c       mercedes     500
4     d       opel         400
5     e       volkswagen   340

This is what I tried:

UPDATE table_1
   SET (name, desc) = (SELECT table_2.name, table_2.desc
                         FROM table_2 t2
                        WHERE table_1.id = table_2.id)
 WHERE EXISTS (
    SELECT 1
      FROM table_2
     WHERE table_1.id = table_2.id )

This is what I got:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(name, desc) = (SELECT table_2.name, table_2.desc                          FROM ' at line 2    0.000 sec

**Please note that my tables are much bigger in reality. PS I'am using Toad.


Solution

  • Using the INSERT on DUPLICATE mechanism would do this in one quite consise query

    INSERT INTO table_1 (`id`, `name`,`desc`,`price`)
        (
         SELECT `t2`.`id`, `t2`.`name`, `t2`.`desc`, `t2`.`price` 
         from table_2 t2 
         where id = t2.id
        )
    ON DUPLICATE KEY UPDATE `name`=`t2`.`name`, 
                            `desc`=`t2`.`desc`, 
                            `price`=`t2`.`price`;