Skip to content
Advertisement

How to Update new tables inside another update query?

I have a legacy system and i have a php file inside of it, updating one table. Now i added a new table to my db and i want to update that table too. The problem is that (for some reasons) i cannot use another query and i have to change the current query.

simplified former query: $q = "UPDATE t1 SET var=$var WHERE id=1";

I can’t use "UPDATE t1,t2 SET t1.var=$var t2.var=$var2 WHERE id=1" since it adds too much processing time. Is it possible to run two update queries in one query? I am using mysql commands in my entire system and i can’t change it to mysqli.

Advertisement

Answer

For anyone coming to this question, there are two simple ways to do this:

Method 1:

UPDATE Books, Orders
SET Orders.Quantity = Orders.Quantity + 2,
    Books.InStock = Books.InStock - 2
WHERE
    Books.BookID = Orders.BookID
    AND Orders.OrderID = 1002;

Method 2 (inner join):

UPDATE t1
INNER JOIN t2 ON t2.t1_id = t1.id
INNER JOIN t3 ON t2.t3_id = t3.id
SET t1.a = 'something',
    t2.b = 42,
    t3.c = t2.c
WHERE t1.a = 'blah';
7 People found this is helpful
Advertisement