小编Jos*_*osh的帖子

选择指定行之前/之后的 N 行

假设我在 Postgres (11.3) 中有一个简单的表:

create table posts
(
    id serial not null,
    created_at timestamp(0)
    constraint posts_pkey
        primary key (id)
);
Run Code Online (Sandbox Code Playgroud)

如果用户请求 id=5869,我需要能够在按列排序的查询中返回该行之前的 N 行和之后的 N 行created_at。如果我们能够假设 越大id,则 越大created_at,我们可以做一些相对简单的事情,如下所示:

(select * from posts where id < 5869 order by id limit 10)
union all
(select * from posts where id >= 5869 order by id limit 11);
Run Code Online (Sandbox Code Playgroud)

但是,我无法假设更高的 id 是最近创建的,我想知道在这种情况下检索该数据的最佳方法是什么。此方法有效,但在 100k 行数据集上速度非常慢:

WITH 
  boundaries AS (
    SELECT *,
           row_number() OVER (ORDER BY created_at DESC) AS …
Run Code Online (Sandbox Code Playgroud)

postgresql

5
推荐指数
1
解决办法
4360
查看次数

标签 统计

postgresql ×1