在 postgres table 上从 select 查询的结果集中获取 n 行

Getting n rows from resultset of select query on a postgres postgres table

我在 get API 中添加分页,需要从 select 查询中获取特定的行号。我怎样才能在 postgresql 中实现这个? 对于 page=2 和 count=10,我想检索第 11-20 行。

select users.id from users, usernotification where usernotification.channel=1 and usernotification.id=users.id;

Postgres 没有行号的固有概念。可能会创建真实的行号,但除非您存储它们,否则它将基于逐个查询。也就是说,以下内容只需要跟踪要显示的页码。它还具有处理向前和向后滚动的优势。

注意: 我已将您的查询修改为使用标准 ANSI 连接语法。你应该采纳它。更容易看到实际需要的东西,也更不容易出错。

   select u.id 
     from users u
     join usernotification un 
       on un.id = u.id and un.channel=1
    order by u.id 
   offset (&page_num-1) * 10 limit 10; 

缺点是如果其他用户删除了先前显示的行,它可能会出现“丢失”的行。如果是这样,您将“错过”后续行数等于删除的行数。例如,在显示第 1-10 行时,另一个用户删除了其中的 5 行,您的页面 2 将显示原始的第 15-24 行,而不是第 11-20 行。
参见 Demo。由于 db<>fiddle 不支持分页,它将 'page forward' 具有先验知识页面控制值。还添加了几个额外的列。