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

前端 未结 11 1235
迷失自我
迷失自我 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:57

    You should first ensure that the column has no UNIQUE index, otherwise mysql will tell you that the constraint is broken during the query. After that you can do things like:

    -- Move #10 down (i.e. swap #10 and #11)
    UPDATE mytable SET display_order =
      CASE display_order
        WHEN 10 THEN 11
        WHEN 11 THEN 10
      END CASE
    WHERE display_order BETWEEN 10 AND 11;
    
    -- Move #4 to #10
    UPDATE mytable SET display_order
      CASE display_order
        WHEN 4 THEN 10
        ELSE display_order - 1
      END CASE
    WHERE display_order BETWEEN 4 AND 10;
    

    But you should actually ensure that you do things in single steps. swapping in two steps will result in broken numbering if not using ids. i.e.:

    -- Swap in two steps will not work as demostrated here:
    
    UPDATE mytable SET display_order = 10 WHERE display_order = 11;
    -- Now you have two entries with display_order = 10
    
    UPDATE mytable SET display_order = 11 WHERE display_order = 10;
    -- Now you have two entries with display_order = 11 (both have been changed)
    

    And here is a reference to the CASE statement of mysql.

提交回复
热议问题