postgresql SQL:按升序选择 N 个“最近的”行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7735419/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:21:37  来源:igfitidea点击:

SQL: select N “most recent” rows in ascending order

sqlsqlitepostgresql

提问by David Wolever

For example, if my data look like this:

例如,如果我的数据如下所示:

timestamp | message
100 | hello
101 | world
102 | foo
103 | bar
104 | baz

How can I select the three most recent rows — 102, 103, 104 — in ascending order?

如何按升序选择最近的三行 - 102、103、104?

The obvious (to me) … LIMIT 3 ORDER BY timestamp DESCwill return the correct rows but the order is incorrect.

显而易见的(对我来说)… LIMIT 3 ORDER BY timestamp DESC将返回正确的行,但顺序不正确。

回答by Mark Byers

Use an inner select to select the correct rows, and an outer select to order them correctly:

使用内部选择来选择正确的行,使用外部选择来正确排序:

SELECT timestamp, message
FROM
(
     SELECT *
     FROM your_table
     ORDER BY timestamp DESC
     LIMIT 3 
) T1
ORDER BY timestamp