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

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

    You could delete an re-insert all the rows - that would do the whole operation in just two queries (or three if you need to select all the data). I wouldn't count on it being faster, and you'd have to do it inside a transaction or you'll be heading for your backups before too long. It could also lead to table fragmentation.

    A better option might be to record each change as a history then do something like this:

    Example, position 10 is moved down two to 12th

    UPDATE table SET display_order = display_order -1 WHERE display_order BETWEEN 10 AND 12
    UPDATE table SET display_order = 12 WHERE row_id = [id of what was row 10]
    

提交回复
热议问题