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

前端 未结 11 1242
迷失自我
迷失自我 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 08:10

    I'm thinking about this problem, and the solution I came up is having a decimal number as order and change the number of the item change for a number between the next and the previous item

    Order    Item
    -----    ----
    1        Original Item 1
    2        Original Item 2
    3        Original Item 3
    4        Original Item 4
    5        Original Item 5
    

    If you change the item 4 to the 2nd position, you get:

    Order    Item
    -----    ----
    1        Original Item 1
    1.5      Original Item 4
    2        Original Item 2
    3        Original Item 3
    5        Original Item 5
    

    If you change the item 3 to the 3rd position, you get:

    Order    Item
    -----    ----
    1        Original Item 1
    1.5      Original Item 4
    1.75     Original Item 3
    2        Original Item 2
    5        Original Item 5
    

    Theoretically there is always a decimal between two decimals, but you could face some storage limits.

    This way you only have to update the row being re-ordered.

提交回复
热议问题