Postgres - 逐页

时间:2016-05-10 17:08:47

标签: sql postgresql pagination

说我有一些数据:

id  |                stage | name
----+----------------------+------
  1 |          pyramid     | act 1
  2 |          pyramid     | act 2
  3 |          pyramid     | act 3
  4 |          other stage | act 4
  5 |          other stage | act 5
  6 |          other stage | act 6
  7 |          other stage | act 7
  8 |          shangri la  | act 8

我希望使用分页将这些数据加载到我的UI中 - 但我希望分页能够处理组而非行数 - 实现此目的的最佳方法是什么?

因此,第1页(如果按section_id分组)将产生:

  1 |          pyramid | act 1
  2 |          pyramid | act 2
  3 |          pyramid | act 3

1 个答案:

答案 0 :(得分:1)

如果您可以准确指定所需的条件,那么只需在WHERE子句中使用过滤器:

select *
from data
where stage = 'pyramid';

否则,如果您需要页码,则需要确定分组条件的等级。你可以这样做:

select *
from data
where stage = (
  select stage
  from (
    select stage, row_number() over ()
    from data
    group by stage
    order by stage
    ) s
  where row_number = <page number>
  )