ali*_*ice 14 postgresql select
我有下表:
CREATE TABLE post (
id bigint primary key,
thread_id bigint,
is_notice boolean,
title text,
content text
)
Run Code Online (Sandbox Code Playgroud)
我使用以下查询显示列表:
SELECT * FROM post ORDER BY is_notice desc, thread_id desc, id
Run Code Online (Sandbox Code Playgroud)
然后,给定由 id(ie SELECT * FROM post where id=3
)选择的帖子,我如何检索下一个和上一个帖子?
bma*_*bma 20
使用 PostgreSQL 的Window Functions,特别是LAG
and LEAD
,应该能够显示表中的上一个和下一个条目。
select *
from (
select id, thread_id, is_notice, title, content,
lag(id) over (order by is_notice desc, thread_id desc, id asc) as prev,
lead(id) over (order by is_notice desc, thread_id desc, id asc) as next
from post
) x
where 3 IN (id, prev, next);
Run Code Online (Sandbox Code Playgroud)
可以在此处找到演示:http : //sqlfiddle.com/#!15/9fd7a/8
归档时间: |
|
查看次数: |
22292 次 |
最近记录: |