日期:2014-05-16  浏览次数:20436 次

关于 oracle 中的rownum陷阱

最近在做关于某一oracle 的sql优化:涉及到关于分页的一些内容。

例如查询top 5 的数据 ?我们需要写:

select * from
(select * from customer order by custcredit)
where rownum < = 5

? 而不是写:

select * from customer order by custcredit where rownum <=5

经测试,前一种写法是对的。而后一种则是随机选出5天,再对其进行排序,可见rownum处理先于order by

Ps:如果我们要找数据库插入第二个之后的数据,直接用

select * from customer where rownum>2?是查不出记录的,原因是由于rownum是一个总是从1开始的伪列,Oracle 认为rownum> n(n>1的自然数)这种条件依旧不成立,所以查不到记录.那如何才能找到第二行以后的记录呀。可以使用以下的子查询方法来解决。注意子查询中的rownum必须要有别名,否则还是不会查出记录来,这是因为rownum不是某个表的列,如果不起别名的话,无法知道rownum是子查询的列还是主查询的列。 SQL>select * from(select rownum no ,* ?from customer )t where no>2; ? ??