Storing item positions (for ordering) in a database efficiently

后端 未结 4 899
遇见更好的自我
遇见更好的自我 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条回答
  •  囚心锁ツ
    2021-02-01 18:25

    Store the order linked-list style. Instead of saving the absolute position, save the ID of the previous item. That way any change only requires you to update two rows.

    movieid | userid  | previousid
       1    |    1    | 
       2    |    1    |    1
       3    |    1    |    4
       4    |    1    |    2
    

    To get the movies in order ...

    SELECT movieid WHERE userid = 1 ORDER BY previousid
    
    -> 1, 2, 4, 3
    

    To (say) move #4 up a space:

    DECLARE @previousid int, @currentid int
    SET @previousid = SELECT previousid FROM movies WHERE movieid = @currentid
    
    -- current movie's previous becomes its preceding's preceding
    UPDATE movies SET previousid = 
        (SELECT previousid FROM movies WHERE movieid = @previousid)
    WHERE movieid = @currentid
    
    -- the preceding movie's previous becomes the current one's previous
    UPDATE movies SET previousid = @currentid WHERE movieid = @previousid
    

    That's still 1 read + 2 writes, but it beats 10,000 writes.

提交回复
热议问题