我试图将表中的前导或尾随x条目转换为特定的id。我目前的尝试确实做得很好但是它看起来很笨重,我想知道是否有办法改进它。
WITH tempTable AS ( SELECT *,ROW_NUMBER() OVER (ORDER BY created DESC) AS RN from byali.posts)
SELECT * from tempTable as nb1 WHERE RN IN (SELECT nb2.RN+i
FROM tempTable AS nb2
CROSS JOIN (SELECT a.n as i FROM generate_series(-10,-1) as a(n)) n
WHERE nb2.id='188d9b6b-e398-407d-9cf4-e75ff121c32a')
这将在条目
的条目前选择10个帖子188d9b6b-e398-407d-9cf4-e75ff121c32a
表格结构:
CREATE TABLE byali.posts
(
id uuid NOT NULL DEFAULT gen_random_uuid(),
title text COLLATE pg_catalog."default",
message text COLLATE pg_catalog."default",
created timestamp with time zone DEFAULT now(),
CONSTRAINT posts_pkey PRIMARY KEY (id)
)
样本数据:
insert into byali.posts (title,message,created) VALUES ('title1','message1','2018-02-11 17:00:56.349611+01'),('title2','message2','2018-02-13 12:22:54.432413+01'),('title3','message3','2018-02-13 14:38:51.997999+01')
答案 0 :(得分:1)
如果创建的列是唯一的,您可以使用以下查询在id = 188d9b6b-e398-407d-9cf4-e75ff121c32a的条目之前获得10个帖子:
select *
from byali.posts
where created < (select created
from byali.posts
where id = '188d9b6b-e398-407d-9cf4-e75ff121c32a')
order by created desc
limit 10;
输入后的10个帖子,id = 188d9b6b-e398-407d-9cf4-e75ff121c32a
select *
from byali.posts
where created > (select created
from byali.posts
where id = '188d9b6b-e398-407d-9cf4-e75ff121c32a')
order by created
limit 10;