2

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.

2 Answers 2

3

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';
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the reply! I made a test like so: UPDATE test SET test.unique_id = store_import.unique_id, test.synced_on = store_import.synced_on FROM store_import WHERE store_import.entry_id = 137 This gives error #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 'FROM store_import WHERE store_import.entry_id = 137' at line 4 Can you see where the problem lies?
Yeah I already changed the solution since I posted it. I mixed up MySQL and MSSQL. The current version is the one. :-)
Ah well. Thanks. Will take a long time getting all 165 columns into query!
You may want to alias the tables to speed up your input. UPDATE foo a, bar b SET a.x=b.x, a.y=b.y ......
1

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

1 Comment

Note JOIN is the same as , in list of table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.