简体   繁体   中英

mySQL: Updating multiple values in a record with a SELECT from another table

Trying to sort out the correct syntax for this UPDATE :

UPDATE `foo` 
   SET (`x`, `y`, `z`) = (SELECT `x`, `y`, `z` 
                            FROM `bar` 
                           WHERE `id` = 'baz');

In the actual query, there are 165 columns so I very much do not want to have to do x = x for each column.

The columns are not a perfect match so SELECT * is not an option.

In MySQL you can add multiple tables to an UPDATE like this:

UPDATE `foo`, `bar`
SET `foo`.`x` = `bar`.`x`, 
    `foo`.`y` = `bar`.`y`, 
    `foo`.`z` = `bar`.`z`
WHERE `id` = 'baz';

You are trying to update items in foo where foo.id = bar.baz?

UPDATE foo JOIN bar
SET foo.x=bar.x, foo.y=bar.y
WHERE foo.id=bar.baz

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