总行数 + 带有限制的选择查询

6
我的问题类似于这个问题:https://stackoverflow.com/questions/4840987/need-a-row-count-after-select-statement-whats-the-optimal-sql-approach">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查询会执行两次?

还有其他方法吗? 附注:我正在使用postgres,我知道mysql有FOUND_ROWS()

1个回答

5

关于:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接