Marcelo Forclaz Marcelo Forclaz - 2 years ago 87
SQL Question

Two updates in one mysql query

I'll try to do my question simple, how do you do the next process in only one MySql query?

$query = "UPDATE news SET main = 1 WHERE id = '$id'";
mysqli_query($this->db_conn, $query);
$query = "UPDATE news SET main = 0 WHERE id <> '$id'";
mysqli_query($this->db_conn, $query);

Only one row has value 1 while for the rest of them is 0

Answer Source

Give this a try:

UPDATE news SET main = CASE
    WHEN id = '$id' THEN 1
    ELSE 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download