rownum max 谁先谁后

Posted by Vincent on December 8, 2009

select max(gmt_create) from t_tname where author_id=:1 and rownum=1;

这个sql是否满足author_id下取最大的时间。
答案是肯定的,不满足
这个sql会先取满足条件的 where author_id=:1 一条记录,再取MAX就没有任何意义了。

但是到author_id上存在索引的情况下,执行计划会是
SORT AGGREGATE
COUNT STOPKEY
FIRST ROW
INDEX RANGE SCAN (MIN/MAX)    DX_FEED_RECEIVE_00_RATED

这样取到的结果又正确了,当然这个可以理解为一种特殊情况。

对于sql中有rownum的需要特别关照 取到的值是否是你想要的,rownum是oracle获取到数据之后的一个伪列

rownum的优先级还是非常高的,请看:

select ..., ROWNUM
  from t
 where <where clause>
 group by <columns>
having <having clause>
 order by <columns>;

Think of it as being processed in this order:

1. The FROM/WHERE clause goes first.
2. ROWNUM is assigned and incremented to each output row from the FROM/WHERE clause.
3. SELECT is applied.
4. GROUP BY is applied.
5. HAVING is applied.
6. ORDER BY is applied.

-- 详情请参考: www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html


This work is licensed under a CC A-S 4.0 International License.