Marcelo Forclaz Marcelo Forclaz - 6 months ago 8x
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


Give this a try:

UPDATE news SET main = CASE
    WHEN id = '$id' THEN 1
    ELSE 0