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

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

    You could try to wrap it into a few statements, I don't think it's possible in a single one. So for example, let's say you are going to update the 10th row. You want every record after 10 to be bumped up.

    UPDATE table SET col=col+1 WHERE col > 10
    UPDATE table SET col=10 WHERE id = X
    ... 
    

    But it's really tough to roll in all logic required. Because some records maybe need a decrement, etc.. You want to avoid duplicates, etc..

    Think about this in terms of developer time vs. gain.

    Because even if someone sorts this once per day, the overhead is minimal, compared to fixing it in a stored procedure, or pseudo-optimizing this feature so you don't run 20 queries. If this doesn't run 100 times a day, 20 queries are perfectly fine.

提交回复
热议问题