如何在 Postgresql 中正确使用 FETCH FIRST?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38467298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to correctly use FETCH FIRST in Postgresql?
提问by Tyler Chong
I was trying to find out how to only select the first element of the SELECT query.
我试图找出如何只选择 SELECT 查询的第一个元素。
It seems alot of people use LIMIT 1 to only select the first one, but that doesn't seem like the best way to do it.
似乎很多人使用 LIMIT 1 只选择第一个,但这似乎不是最好的方法。
I was reading up on SELECT in the Postgresql docs, and it seems there is an option for a FETCH statement but I can't find any examples online, could someone explain to me how to correctly use it?
我正在阅读 Postgresql 文档中的 SELECT ,似乎有一个 FETCH 语句选项,但我在网上找不到任何示例,有人可以向我解释如何正确使用它吗?
回答by jmelesky
The following statements are equivalent:
以下语句是等效的:
SELECT * FROM foo LIMIT 10;
and
和
SELECT * FROM foo FETCH FIRST 10 ROWS ONLY;
ROWS
is interchangeable with ROW
, which makes fetching just 1 a little more grammatically consistent.
ROWS
可与 互换ROW
,这使得仅获取 1 在语法上更加一致。
FETCH FIRST X ROWS ONLY
is part of the SQL standard, while, to my recollection, LIMIT
is not. LIMIT
is very popular, and much more terse, so it is also supported by postgres.
FETCH FIRST X ROWS ONLY
是 SQL 标准的一部分,而据我所知,LIMIT
不是。LIMIT
非常流行,而且更加简洁,因此 postgres 也支持它。
Edited to add: The two statements are only syntactically different. They generate exactly the same plans:
编辑添加:这两个语句仅在语法上不同。它们生成完全相同的计划:
=# explain select * from foo fetch first 10 row only;
QUERY PLAN
-------------------------------------------------------------
Limit (cost=0.00..0.22 rows=10 width=68)
-> Seq Scan on foo (cost=0.00..18.50 rows=850 width=68)
=# explain select * from foo limit 10;
QUERY PLAN
-------------------------------------------------------------
Limit (cost=0.00..0.22 rows=10 width=68)
-> Seq Scan on foo (cost=0.00..18.50 rows=850 width=68)