简体   繁体   中英

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 .

You can use below code to update 2 table at same time. :-)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}

$sql = "UPDATE t1 SET var=$var WHERE id=1";
$sql2 = "UPDATE t2 SET var=$var WHERE id=1";

if ($conn->query($sql) === TRUE) {
    echo "t1 updated successfully";
} else {
    echo "Error updating t1: " . $conn->error;
}

if ($conn->query($sql2) === TRUE) {
    echo "t2 updated successfully";
} else {
    echo "Error updating t2: " . $conn->error;
}

$conn->close();
?>

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';

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