在应用LIMIT之前获得结果计数的最佳方法 [英] Best way to get result count before LIMIT was applied

查看:106
本文介绍了在应用LIMIT之前获得结果计数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当分页来自数据库的数据时,您需要知道将呈现多少页来呈现页面跳转控件.

When paging through data that comes from a DB, you need to know how many pages there will be to render the page jump controls.

当前,我通过运行两次查询来完成此任务,一次包裹在count()中以确定总结果,第二次使用限制以仅获取我当前页面所需的结果.

Currently I do that by running the query twice, once wrapped in a count() to determine the total results, and a second time with a limit applied to get back just the results I need for the current page.

这似乎效率低下.是否有更好的方法来确定在应用LIMIT之前将返回多少结果?

This seems inefficient. Is there a better way to determine how many results would have been returned before LIMIT was applied?

我正在使用PHP和Postgres.

I am using PHP and Postgres.

推荐答案

纯SQL

自2008年以来,情况发生了变化.您可以使用窗口功能在一次查询中获得全部计数有限的结果.在 2009年PostgreSQL 8.4中引入.

Pure SQL

Things have changed since 2008. You can use a window function to get the full count and the limited result in one query. Introduced with PostgreSQL 8.4 in 2009.

SELECT foo
     , count(*) OVER() AS full_count
FROM   bar
WHERE  <some condition>
ORDER  BY <some col>
LIMIT  <pagesize>
OFFSET <offset>;

请注意,此可能比没有总数的情况要昂贵得多.必须对所有行进行计数,可能的快捷方式仅从匹配的索引中获取最前面的行可能不再有用.
对于小型表或full_count< = OFFSET + LIMIT没什么关系.对于更大的full_count来说很重要.

Note that this can be considerably more expensive than without the total count. All rows have to be counted, and a possible shortcut taking just the top rows from a matching index may not be helpful any more.
Doesn't matter much with small tables or full_count <= OFFSET + LIMIT. Matters for a substantially bigger full_count.

小写 :当OFFSET至少等于基本查询的行数时, 无行 返回.因此,您也不会得到full_count.可能的选择:

Corner case: when OFFSET is at least as great as the number of rows from the base query, no row is returned. So you also get no full_count. Possible alternative:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆