Storing item positions (for ordering) in a database efficiently

后端 未结 4 909
遇见更好的自我
遇见更好的自我 2021-02-01 17:40

Scenario:

There is a database of movies a user owns, movies are displayed on a page called \"my-movies\", the movies can be displayed in the order that the user desires.

4条回答
  •  -上瘾入骨i
    2021-02-01 18:25

    ID   NAME  POSITION
    7     A       1
    9     B       2
    13    C       3
    15    D       4
    21    F       5
    

    Given the current scenario if we want to move item D to position 2 we can search for the interval between 2(the position we want to move the item) and 4 (The item's current position) and write a query to ADD +1 to the position of every element inside this interval hence in this case we can do the following steps:

    1. Search for items in the interval where position >= 2 AND position < 4, and add a +1 to its position
    2. Set Item D position to 2.

    This will generate that know : A->1, B->3, C-> 4, D->2, F->5

    In case we want to move B to D then we need to do the opposite and apply a -1 instead.

    1. Search for items in the interval where position > 2 AND position <= 4 substract -1 from its position
    2. Set item position to 4

    When deleting an Item from the table we need to update every item where its position is greater than the position of the element that's being deleted.

    And when creating and Item its position is equal to the COUNT of every item +1.

    DISCLAIMER: If you have a really big amount maybe this solution is not what you want, but for most cases will do. Normally a user wont move an item from position 10000 to position 2 but if instead the users delete item 1 then the query will substract -1 to the 9999 remaining items. If this is your scenario then maybe the solution with the linked list is probably the best for you, but then ordering will be more challenging because you need to go item by item to see who's next on the list.

    Example querys

    -- MOVE DOWN
    UPDATE movie SET position = position-1  WHERE position <= 18 AND position > 13 AND id > 0;
    UPDATE movie SET position = 18 WHERE id = 130;
    
    -- MOVE UP
    UPDATE movie SET position = position+1  WHERE position < 18 AND position >= 13 AND id > 0;
    UPDATE movie SET position = 13 WHERE id = 130;
    

提交回复
热议问题