postgresql - postgres 按值偏移而不是数字

标签 postgresql subquery offset

我有一个至少包含“名称”列和“序号位置”列的表格。我希望从用户输入的某一行开始循环每一行。假设用户输入“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');

最佳答案

不幸的是,您必须查询表格以找到给定 nameordinal_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/

相关文章:

Node.js postgreSQL 集成 - TypeError : Cannot read property 'status' of undefined

ruby-on-rails - Rails 帮助 ActionView::Template::Error 提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换

readline - 为什么不是所有的 readline 快捷方式都适用于 psql(或 IRB,或 Rails 控制台)?

c# - 我该怎么做才能停止出现连接池错误

javascript - 滚动 iframe 内的 jQuery UI dropzone 错误偏移

SQL:帮助嵌套查询

Mysql嵌套查询传递一个值给嵌套查询

sql - 仅使用 SQL 返回 pre-UPDATE 列值

jquery - 函数 scrollTo(id) 中的 jquery 偏移问题

ffmpeg 在输出中设置时间码偏移