Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do three table JOINs in an UPDATE query?

Tags:

join

mysql

I asked a question and got this reply which helped.

   UPDATE TABLE_A a JOIN TABLE_B b    ON a.join_col = b.join_col AND a.column_a = b.column_b    SET a.column_c = a.column_c + 1 

Now I am looking to do this if there are three tables involved something like this.

    UPDATE tableC c JOIN tableB b JOIN tableA a 

My question is basically... is it possible to do three table joins on an UPDATE statement? And what is the correct syntax for it?

Do I do the following?

 JOIN tableB, tableA  JOIN tableB JOIN tableA 
like image 750
Ricky Avatar asked Mar 04 '13 19:03

Ricky


People also ask

Can we use joins in UPDATE query?

The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.

Can you do 3 joins in SQL?

It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.


2 Answers

The answer is yes, you can.

Try it like this:

UPDATE TABLE_A a     JOIN TABLE_B b ON a.join_col = b.join_col AND a.column_a = b.column_b     JOIN TABLE_C c ON [condition] SET a.column_c = a.column_c + 1 

For a general update join:

UPDATE TABLEA a JOIN TABLEB b ON a.join_colA = b.join_colB SET a.columnToUpdate = [something] 
like image 198
echo_Me Avatar answered Sep 29 '22 11:09

echo_Me


An alternative way of achieving the same result is not to use the JOIN keyword at all.

UPDATE TABLE_A, TABLE_B SET TABLE_A.column_c = TABLE_B.column_c + 1 WHERE TABLE_A.join_col = TABLE_B.join_col 
like image 26
Matas Vaitkevicius Avatar answered Sep 29 '22 12:09

Matas Vaitkevicius