postgres 按值偏移而不是数字
postgres offset by value not number
我有一个 table,其中至少有一个 "name" 列和一个 "ordinal_position" 列。我希望从用户输入的某一行开始循环每一行。假设用户输入 "John",他的 ordinal_position 是 6(共 10 个)。如何在不使用子查询的情况下仅循环最后 4 行?我试过使用 "OVER()" window 函数,但它似乎不适用于查询的偏移量部分,并且相同的偏移量只需要数字(据我所知)而不是字符串。
编辑(响应 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');
不幸的是,您必须查询 table 才能找到给定 name
的 ordinal_position
。
但是,不要使用 offset
。您可以在 where
子句中执行此操作,对于较大的 tables 它会快得多:
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)
我有一个 table,其中至少有一个 "name" 列和一个 "ordinal_position" 列。我希望从用户输入的某一行开始循环每一行。假设用户输入 "John",他的 ordinal_position 是 6(共 10 个)。如何在不使用子查询的情况下仅循环最后 4 行?我试过使用 "OVER()" window 函数,但它似乎不适用于查询的偏移量部分,并且相同的偏移量只需要数字(据我所知)而不是字符串。
编辑(响应 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');
不幸的是,您必须查询 table 才能找到给定 name
的 ordinal_position
。
但是,不要使用 offset
。您可以在 where
子句中执行此操作,对于较大的 tables 它会快得多:
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)