Updating display order of multiple MySQL rows in one or very few queries

前端 未结 11 1244
迷失自我
迷失自我 2021-02-01 07:43

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

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 07:49

    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.

提交回复
热议问题