Optimizing queries for the next and previous element

前端 未结 11 931
耶瑟儿~
耶瑟儿~ 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 11:47

    I'm not sure whether I understood right, so if not, just tell me ;)

    Let's say, that the givens are the query for the sorted list and the current offset in that list, i.e. we have a $query and an $n.

    A very obvious solution to minimize the queries, would be to fetch all the data at once:

    list($prev, $current, $next) = DB::q($query . ' LIMIT ?i, 3', $n - 1)->fetchAll(PDO::FETCH_NUM);
    

    That statement fetches the previous, the current and the next elements from the database in the current sorting order and puts the associated information into the corresponding variables.

    But as this solution is too simple, I assume I misunderstood something.

提交回复
热议问题