Reputation: 24061
I have a flag in my database called published, I set this to 1 for a published row. My question is , is there a way to set all other rows to 0 and set a particular row to 1 with just one query.
At the moment im using:
$db->query("UPDATE my_table SET published = '0'");
$db->query("UPDATE my_table SET published = '1' WHERE id = '$id'");
Upvotes: 3
Views: 494
Reputation: 35927
In MySQL, there's no boolean type (conditions return an integer), so this works too :
UPDATE my_table
SET published = (id = $id);
id = $id
returns 0 if $id is different than id, else 1.
Upvotes: 0
Reputation: 14333
Use a CASE Statement
UPDATE my_table
SET published = CASE
WHEN id = '$id' THEN 1
ELSE 0 END
Upvotes: 1