I have a table with say 20 rows each with a number for display order (1-20).
SELECT * FROM `mytable` ORDER BY `display_order` DESC;
From an adm
soulmerge's answer made me think and I think this is a better solution. What you need to do is select the rows with the id using IN() and then use CASE to set the value.
UPDATE mytable SET display_order =
CASE id
WHEN 10 THEN 1
WHEN 23 THEN 2
WHEN 4 THEN 3
END CASE
WHERE id IN (10, 23, 4)
I have a need for this in my current app. In PHP, I'm getting a serialized (and ordered) set of id's from jQuery UI's built-in Sortable feature. So the array looks like this:
$new_order = array(4, 2, 99, 15, 32); // etc
To generate the single MySQL update query, I do this:
$query = "UPDATE mytable SET display_order = (CASE id ";
foreach($new_order as $sort => $id) {
$query .= " WHEN {$id} THEN {$sort}";
}
$query .= " END CASE) WHERE id IN (" . implode(",", $new_order) . ")";
The "implode" at the end just gives me my ID list for IN(). This works beautifully for me.