SQL 如何限制 PostgreSQL SELECT 中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1133944/
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 limit rows in PostgreSQL SELECT
提问by Dan Mertz
What's the equivalent to SQL Server's TOP
or DB2's FETCH FIRST
or mySQL's LIMIT
in PostgreSQL?
PostgreSQL 中的SQL ServerTOP
或 DB2FETCH FIRST
或 mySQL 的等价物是什么LIMIT
?
回答by Sinan Taifour
回答by mongotop
You could always add the OFFSET
clause along with LIMIT
clause.
您始终可以将OFFSET
子句与LIMIT
子句一起添加。
You may need to pick up a set of records from a particular offset. Here is an example which picks up 3 records starting from 3rd position:
您可能需要从特定偏移量中获取一组记录。这是一个从第 3 个位置开始选取 3 个记录的示例:
testdb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2;
This would produce the following result:
这将产生以下结果:
id | name | age | address | salary
----+-------+-----+-----------+--------
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
Full explanation and more examples check HERE
完整的解释和更多的例子检查这里
回答by Sarath
Apart from limit you could use Fetch First as well. Your question already had the answer
除了限制之外,您还可以使用 Fetch First。你的问题已经有了答案
Select * from users FETCH FIRST 5 ROWS ONLY
回答by Vlad Mihalcea
On PostgreSQL, there are two ways to achieve this goal.
在 PostgreSQL 上,有两种方法可以实现这个目标。
SQL Standard
SQL标准
The first option is to use the SQL:2008 standard way of limiting a result set using the FETCH FIRST N ROWS ONLY
syntax:
第一个选项是使用 SQL:2008 标准方法来限制使用以下FETCH FIRST N ROWS ONLY
语法的结果集:
SELECT
title
FROM
post
ORDER BY
id DESC
FETCH FIRST 50 ROWS ONLY
The SQL:2008 standard syntax is supported since PostgreSQL 8.4.
自 PostgreSQL 8.4 起支持 SQL:2008 标准语法。
PostgreSQL 8.3 or older
PostgreSQL 8.3 或更高版本
For PostgreSQL 8.3 or older versions, you need to the LIMIT clause to restrict the result set size:
对于 PostgreSQL 8.3 或更早版本,您需要使用 LIMIT 子句来限制结果集大小:
SELECT
title
FROM
post
ORDER BY
id DESC
LIMIT 50
For more details about this topic, check out this article.
有关此主题的更多详细信息,请查看这篇文章。