我有一个至少包含“名称”列和“序号位置”列的表格。我希望从用户输入的某一行开始循环每一行。假设用户输入“John”,他的 ordinal_position 是 6(总共 10 个)。如何在不使用子查询的情况下仅循环最后 4 行?我试过使用“OVER()”窗口函数,但它似乎不适用于查询的偏移量部分,并且相同的偏移量只需要数字(据我所知)而不是字符串。
编辑(响应 klin):
INSERT INTO foo(id,name,ordinal_position) VALUES
(DEFAULT,'Peter',1),
(DEFAULT,'James',2),
(DEFAULT,'Freddy',3),
(DEFAULT,'Mark',4),
(DEFAULT,'Jack',5),
(DEFAULT,'John',6),
(DEFAULT,'Will',7),
(DEFAULT,'Robert',8),
(DEFAULT,'Dave',9),
(DEFAULT,'Michael',10);
所以在我的 FOR 中,因为用户输入了“John”,所以我想遍历 Will-Michael。类似于以下内容但没有子查询:
SELECT * FROM foo ORDER BY ordinal_position OFFSET
(SELECT ordinal_position FROM foo WHERE name='John');
最佳答案
不幸的是,您必须查询表格以找到给定 name
的 ordinal_position
。
但是,不要使用 offset
。您可以在 where
子句中执行此操作,对于大型表,它会快得多:
select *
from foo
where ordinal_position > (select ordinal_position from foo where name = 'John')
order by ordinal_position;
id | name | ordinal_position
----+---------+------------------
7 | Will | 7
8 | Robert | 8
9 | Dave | 9
10 | Michael | 10
(4 rows)
关于postgresql - postgres 按值偏移而不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38703099/