关于Oracle的rownum


1.给12个id按升序排序,取出排序后的前5个id。

select * from (查询语句) where rownum <=5

Oracle中的rownum的是在取数据的时候产生的序号

  1. select rownum,id from t_busi_presend_mx order by id   

(注:下面结果中,id是已经按照升序排序的)
    ROWNUM    ID
---------- --------------------
         9        20111028094601201693
         8        20111028094601888130
        10       20111028094605946169
         4        20111028094605984087
         7        20111028110758617803
        11       20111028110758930318
         1        20111031064620139463
         2        20111031070024670965
         3        20111031072450370812
         5        20111101112559541615
        12       20111101112605330425
         6        20111101112605775938

可以看出,rownum并不是按照id列来生成的序号。系统是按照记录插入时的顺序给记录排的号,rowid也是顺序分配的。为了解决这个问题,必须使用子查询:

  1. select * from (select rownum,id from t_busi_presend_mx order by id ) where rownum<=5  

    ROWNUM    ID
---------- --------------------
         9      20111028094601201693
         8      20111028094601888130
        10     20111028094605946169
         4      20111028094605984087
         7      20111028110758617803

可以看出,忽略前面的rownum,后面取出的id,确实是我需要的,排序后的前5个id。

2.更新中间100行数据:

  1. update t_busi_presend_mx set codetype='1' where rowid in (  
  2. select t.row_id from(  
  3. select rownum rn,rowid row_id from t_busi_presend_mx   
  4. ) t where t.rn>=101 and t.rn<=199  
  5. )  

相关内容