Storing item positions (for ordering) in a database efficiently

后端 未结 4 906
遇见更好的自我
遇见更好的自我 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:31

    I've been struggling with what best to do with this situation and have come to the realisation that BY FAR the best solution is a list/array of the movies in the order you want them eg;

    userId, moviesOrder

    1 : [4,3,9,1...]

    obviously you will serialise your array.

    'that feels... inefficient'?

    consider the user had a list of 100 movies. Searching by position will be one database query, a string to array conversion and then moviesOrder[index]. Possibly slower than a straight DB lookup but still very very fast.

    OTOH, consider if you change the order;

    with a position stored in the db you need up to 100 row changes, compared to an array splice. The linked list idea is interesting but doesn't work as presented, would break everything if a single element failed, and looks a hell of a lot slower too. Other ideas like leaving gaps, use float are workable although a mess, and prone to failure at some point unless you GC.

    It seems like there should be a better way to do it in SQL, but there really isn't.

提交回复
热议问题