oracle rownum的使用
选择表中的某一行记录:(理解:rownum是oracle系统顺序分配为从查询返回的行的编号)
select * from (select rownum a,t.* from testtab t) where a=2;
select * from (select rownum a,t.* from testtab t) where a=3;
select * from (select rownum a,t.* from testtab t) where a=4;
不能为:
select * from (select rownum,t.* from testtab t) where rownum=2;或
select * from testtab where rownum=2;
返回多行记录:
select * from testtab where rownum<=10;
返回某段记录:(如取记录表中4-10行)
select * from (select rownum no,testtab.* from testtab where rownum<=10) where no>=4;
返回有条件且经过排序的某段记录:
select rownum num1,tt.* from
(select rownum num,t.* from
(select EcodeInfo.* from EcodeInfo where a=1 order by ecode desc) t) tt
where num>19 and rownum<20
以为oracle是先提取记录再排序的,而oracle的rownum是在提取记录就已经生成,它先于排序操作,所以必须使用子查询先排序。
不能为:
select * from tsettab where rownum>10;
返回最后一行记录:
select * from (select rownum a,t.* from testtab t) where a=(select count(*) from testtab);
返回最后N行记录:
select * from (select rownum a,t.* from testtab t) where a=(select count(*)-N from testtab);
在oracle数据库中查询结果的行号使用伪列ROWNUM表示(从1开始)。但rownum是在查询之后排序之前赋值的,所以查询employee按birthday排序的第100到120条记录应该这么写:
1. select * from(
2.
3. select my_table.*, rownum as my_rownum from (
4.
5. select name, birthday from employee order by birthday
6.
7. )my_table where rownum <120
8.
9. ) where my_rownum>=100
select * from( select my_table.*, rownum as my_rownum from ( select name, birthday from employee order by birthday )my_table where rownum <120) where my_rownum>=100
另外对记录的页数算法应该是:
page = (rowCounts + pageSize-1) /pageSize;
分页写法:
select *
from (select r.*, rownum rownum_
from (select t.* from filemanager_hzc t) r
where rownum < 10)
where rownum_ = 3
select s.*,rownum from(
select t.*,rownum rownum_ from filemanager_hzc t where rownum >1
) s where rownum_ <8