假设我有以下数据库表:
record_id | record_date | record_value
-----------+-------------+--------------
1 | 2010-05-01 | 195.00
2 | 2010-07-01 | 185.00
3 | 2010-09-01 | 175.00
4 | 2010-05-01 | 189.00
5 | 2010-06-01 | 185.00
6 | 2010-07-01 | 180.00
7 | 2010-08-01 | 175.00
8 | 2010-09-01 | 170.00
9 | 2010-10-01 | 165.00
我想用record_date ASC排序的数据获取最后5行。这很容易做到:
SELECT * FROM mytable ORDER BY record_date ASC LIMIT 5 OFFSET 4
哪会给我:
record_id | record_date | record_value
-----------+-------------+--------------
6 | 2010-07-01 | 180.00
7 | 2010-08-01 | 175.00
3 | 2010-09-01 | 175.00
8 | 2010-09-01 | 170.00
9 | 2010-10-01 | 165.00
但是当我不知道有多少记录并且无法计算4的幻数时,我该怎么做呢?
我已尝试过此查询,但如果记录少于5条,则会导致OFFSET为负,这是无效的:
SELECT * FROM mytable ORDER BY record_date ASC LIMIT 5
OFFSET (SELECT COUNT(*) FROM mytable) - 5;
那我该怎么做呢?
答案 0 :(得分:73)
为什么不以相反的方式订购?
SELECT * FROM mytable ORDER BY record_date DESC LIMIT 5;
如果您不想在应用程序中正确翻回,可以嵌套查询并翻转它们两次:
SELECT *
FROM (SELECT * FROM mytable ORDER BY record_date DESC LIMIT 5)
ORDER BY record_date ASC;
......结果证明这是一个相当便宜的操作。
答案 1 :(得分:10)
这应该有效:
WITH t AS (
SELECT * FROM mytable ORDER BY record_date DESC LIMIT 5
)
SELECT * FROM t ORDER BY record_date ASC;
答案 2 :(得分:0)
如果您不想使用订单:
select * from something Offset (select case when count(id)>10 then count(id)-10 end from something)