【问题标题】:Total row count + select with limit总行数 + 限制选择
【发布时间】:2013-12-04 19:54:02
【问题描述】:

我的问题与此类似: Need a row count after SELECT statement: what's the optimal SQL approach?

但我想从查询中获取总行数,然后使用 limit 创建分页,所以我不能使用返回的行。 从一个简单的查询:

select * from res_groups

我进入了这个:

select a.*, (select count(1) from (select * from res_groups) e) total 
from (select * from res_groups) a limit 10 offset 10;

或者我可以使用简单的方法并进行两个查询:

select * from res_groups limit 10;
select count(*) from res_groups;

第一个查询是否会执行?恐怕 res_groups 的查询会被执行两次?

还有其他方法吗? ps:我用的是postgres,我知道mysql有FOUND_ROWS()

【问题讨论】:

    标签: postgresql select count


    【解决方案1】:

    怎么样:

    WITH  a AS (select *, count(*) over (range unbounded preceding)
             FROM resgroups)
    SELECT * from a order by foo limit 10 offset 10;
    

    现在,我认为您实际上最好将其分成两个查询,因为看起来您正在有效地进行分页。如果您首先选择 count(*),然后决定需要多少页(并可能缓存该结果),那么您后续的部分查询可以使用索引,但在这种情况下,每组 10 个都需要完整的顺序扫描.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多