ORM or something to handle SQL tables with an order column efficiently

后端 未结 2 1302
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 00:29

I got an Java application using SQL tables that contains an ordered list of entities, ordered by an order column. I would like to add/remove things in/from the middle of the

2条回答
  •  被撕碎了的回忆
    2021-01-03 01:22

    If you really want to end up with a continuous sequential order, you can do it like this:

    First of all, multiply the sortorder by say 1000

    UPDATE testtable SET sortorder = sortorder * 1000
    

    Now do your inserts and insert suitable sortorder values to have the new entries in the right place.

    Now do a table update and update the values using the ROW_NUMBER function

    UPDATE testtable
    SET sortorder = subq.newsortorder
    FROM
      (
      SELECT
        ID as innerID,
        ROW_NUMBER() OVER(ORDER BY sortorder ASC) as newsortorder
      FROM testtable
      ) subq
    WHERE subq.innerID = ID
    

    The ID is selected as innerID as the updated table can't be aliased and the ID column would otherwise end up ambiguous.

    This is updating the sortorder with the row's number when sorted by sortorder.

提交回复
热议问题