postgresql - 从 Postgresql View 获取下一条记录

标签 postgresql next

我已经根据我的要求创建了一个 View someView

ID  |   name
3   |    A
4   |    F
8   |    G
13  |    E
26  |    Z

当我在 where 条件下传递 ID 时,我需要从 View 中获取下一条记录 IE。如果我通过 4 我应该回到 8 。另外,如果我传递最后一个 ID,它应该返回第一条记录 IE。如果我超过 26,我应该回到 3。

我一直在尝试使用滞后和超前,但没有任何效果。我也试过这个

DECLARE aaa SCROLL CURSOR FOR SELECT ID FROM someView where ID > someValue;
fetch 1 from aaa

在这种情况下,我确实获得了下一个值,但如果我传递了最后一个 ID,它不会获得结果。 那我该怎么办呢??还有其他方法可以解决我的问题吗?

提前致谢。

最佳答案

像这样:

with next_entry as (
   select *
   from sometable
   where id > 26 -- change the desired value here 
   order by id
   limit 1
)
select *
from next_entry
union all
select *
from sometable
where not exists (select 1 from next_entry)
limit 1;

它可能不是很有效,但应该可以。

关于postgresql - 从 Postgresql View 获取下一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193375/

相关文章:

javascript - .next (".myClass") 不工作 Jquery

ruby - 跳过 ruby​​ 中 yield block 的迭代

java - 为什么我需要在 ListIterator 中调用 previous() 两次才能进行 'reverse' 迭代?

postgresql - 如何防止在 PostgreSQL 中仅在一个表上进行预写日志记录?

mysql - MySQL 结果集上 Next 按钮的高效算法

python - 带有 "next( c for c in l if )"的 python 语句的含义

java - SQL INSERT 带有多行循环

sql - select count(field) 和 select field,count 是在同一行吗?

postgresql - Postgres 中的 Go 和 IN 子句

postgresql - 如何在 Aqueduct 和 Postgres 中使用不同的表名