oracle的rownum是可以通过select rownum ... from ... 选择出来的,它不是表本身的属性,它是一个伪列,当有一条记录被查询出来时,它的rownum就是1,有第二条记录出来时,rownum就为2。 也就是说它是当结果集被返回时才赋予的,
比如 select rownum,pesn_id from person where sex='woman'
与 select rownum,pesn_id from person where sex='man' 这两条sql语句返回的值完全不一样,但是rownum始终是从1开始递增的。
我们去sql语句的第一条记录时会用到where rownum=1 ,但是rownum>5不会出现任何数据,这不是语句出错,而是查不到结果。如上,只有当第一条记录返回时rownum才会加1,但rownum=1的这条结果是不满足rownum>5这个条件的,所以不会查询出来。而第二条记录返回时,由于rownum=1的记录没有所以这条记录的rownum依旧为1,同样的其他记录也不会选出来。
这就是为什么rownum 的大于条件不会出数据,而小于会出数据,包括=,!=,>=,<=等;
因为rownum 的特性,它是不能用来直接排序的
select rownum as num,cot_gw_cont,gwcon_key,create_date from cot_gw_main order by gwcon_key
必须使用子查询
select rownum,cot_gw_cont,gwcon_key,create_date from ( select * from cot_gw_main order by gwcon_key)
如果要取返回数据的第m(M>1)行到第n行,oracle没有mysql的limit,通常的方法就是利用上面讲的子查询,先选出rownum<n的数据,然后再已有数据的基础上选出rownum>m的数据(这是rownum已经存在,就会有记录)
select num,cot_gw_cont,gwcon_key,create_date from
( select rownum as num,cot_gw_cont,gwcon_key,create_date from cot_gw_main where rownum<10 order by gwcon_key )
where num>5
注意:子查询的rownum必须换名,不然父查询依然没有数据