Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL update a joined table

I want to update a table in a statement that has several joins. While I know the order of joins doesn't really matter (unless you you are using optimizer hints) I ordered them a certain way to be most intuitive to read. However, this results in the table I want to update not being the one I start with, and I am having trouble updating it.

A dummy example of what I'd like to do is something like:

UPDATE b FROM tableA a JOIN tableB b    ON a.a_id = b.a_id JOIN tableC c    ON b.b_id = c.b_id SET b.val = a.val+c.val WHERE a.val > 10     AND c.val > 10; 

There are many posts about updating with joins here however they always have table being updated first. I know this is possible in SQL Server and hopefully its possible in MySQL Too!

like image 376
Aaron Silverman Avatar asked Nov 30 '11 19:11

Aaron Silverman


People also ask

Can you update a joined table?

SQL Server UPDATE JOIN syntaxFirst, specify the name of the table (t1) that you want to update in the UPDATE clause. Next, specify the new value for each column of the updated table. Then, again specify the table from which you want to update in the FROM clause.

Can we use join in update query in MySQL?

In MySQL, you can use the JOIN clauses in the UPDATE statement to perform the cross-table update.

Can you update or delete data in a table using a join?

Using SQL Server, all UPDATE or DELETE statements can only change data in one table. If you need to update rows in more than one table, you need to write a separate statement for each of them.


1 Answers

The multi-table UPDATE syntax in MySQL is different from Microsoft SQL Server. You don't need to say which table(s) you're updating, that's implicit in your SET clause.

UPDATE tableA a JOIN tableB b    ON a.a_id = b.a_id JOIN tableC c    ON b.b_id = c.b_id SET b.val = a.val+c.val WHERE a.val > 10     AND c.val > 10; 

There is no FROM clause in MySQL's syntax.

UPDATE with JOIN is not standard SQL, and both MySQL and Microsoft SQL Server have implemented their own ideas as an extension to standard syntax.

like image 67
Bill Karwin Avatar answered Sep 17 '22 14:09

Bill Karwin