要查询Oracle中的前n行,通常使用ROWNUM.所以以下查询似乎没问题(最近5次付款):
select a.paydate, a.amount
from (
select t.paydate, t.amount
from payments t
where t.some_id = id
order by t.paydate desc
) a
where rownum <= 5;
Run Code Online (Sandbox Code Playgroud)
但是对于非常大的桌子来说,效率很低 - 对我来说它运行大约10分钟.所以我尝试了其他查询,最后我得到了一个运行不到一秒钟的查询:
select *
from (
select a.*, rownum
from (select t.paydate, t.amount
from payments t
where t.some_id = id
order by t.paydate desc) a
)
where rownum <= 5;
Run Code Online (Sandbox Code Playgroud)
为了弄清楚发生了什么,我查看了每个查询的执行计划.对于第一个查询:
SELECT STATEMENT, GOAL = ALL_ROWS 7 5 175
COUNT STOPKEY
VIEW 7 5 175
TABLE ACCESS BY INDEX ROWID 7 …Run Code Online (Sandbox Code Playgroud)