简体   繁体   中英

MySQL Update Multiple Columns with IF ELSE Statement in PHP in single Query

I have two MySql Queries in PHP. I want to merge them ino one two reduce database load.

$sql1 = "UPDATE doorshippers_products 
        SET status='2', price='".$pp."', stock='0', timestemp='".$time."' 
        WHERE sku=$skuu AND price!=$pp";

$conn->query($sql1);


$sql2 = "UPDATE doorshippers_products 
        SET timestemp='".$time."' WHERE 
        sku=$skuu AND price=$pp";

$conn->query($sql2);        


I want to merge them into one using if/else

You can use IF and set the column back to the same value in one condition, otherwise the new value.

$sql1 = "UPDATE doorshippers_products 
        SET status=IF(price = $pp, status, '2'), 
        price='".$pp."', 
        stock=IF(price = $pp, stock, '0'), 
        timestemp='".$time."' 
        WHERE sku=$skuu";

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