Optimizing queries for the next and previous element

前端 未结 11 1073
耶瑟儿~
耶瑟儿~ 2021-01-30 11:33

I am looking for the best way to retrieve the next and previous records of a record without running a full query. I have a fully implemented solution in place, and would like to

11条回答
  •  渐次进展
    2021-01-30 12:04

    I have an idea somewhat similar to Jessica's. However, instead of storing links to the next and previous sort items, you store the sort order for each sort type. To find the previous or next record, just get the row with SortX=currentSort++ or SortX=currentSort--.

    Example:

    Type     Class Price Sort1  Sort2 Sort3
    Lettuce  2     0.89  0      4     0
    Tomatoes 1     1.50  1      0     4
    Apples   1     1.10  2      2     2
    Apples   2     0.95  3      3     1
    Pears    1     1.25  4      1     3
    

    This solution would yield very short query times, and would take up less disk space than Jessica's idea. However, as I'm sure you realize, the cost of updating one row of data is notably higher, since you have to recalculate and store all sort orders. But still, depending on your situation, if data updates are rare and especially if they always happen in bulk, then this solution might be the best.

    i.e.

    once_per_day
      add/delete/update all records
      recalculate sort orders
    

    Hope this is useful.

提交回复
热议问题