总行数+选择限制

时间:2013-11-20 17:12:43

标签: postgresql select count

我的问题与此类似: 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()

1 个答案:

答案 0 :(得分:2)

怎么样:

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

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

相关问题