duanhemou9834 2008-09-09 19:40
浏览 48
已采纳

在使用SQL查询时,对网站进行分页的最有效方法是什么?

I am trying to paginate the results of an SQL query for use on a web page. The language and the database backend are PHP and SQLite.

The code I'm using works something like this (page numbering starts at 0)

http://example.com/table?page=0

page = request(page)
per = 10 // results per page
offset = page * per

// take one extra record so we know if a next link is needed
resultset = query(select columns from table where conditions limit offset, per + 1)

if(page > 0) show a previous link
if(count(resultset) > per) show a next link

unset(resultset[per])

display results

Are there more efficient ways to do pagination than this?

One problem that I can see with my current method is that I must store all 10 (or however many) results in memory before I start displaying them. I do this because PDO does not guarantee that the row count will be available.

Is it more efficient to issue a COUNT(*) query to learn how many rows exist, then stream the results to the browser?

Is this one of those "it depends on the size of your table, and whether the count(*) query requires a full table scan in the database backend", "do some profiling yourself" kind of questions?

  • 写回答

4条回答 默认 最新

  • douqi0090 2008-09-09 19:50
    关注

    i'd suggest just doing the count first. a count(primary key) is a very efficient query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable