开发者

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

开发者 https://www.devze.com 2023-04-12 04:39 出处:网络
For example, if my data look like this: timestamp | message 100 | hello 101 | world 102 | foo 103 | bar 104 | baz

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 m开发者_Python百科ost recent rows — 102, 103, 104 — in ascending order?

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号