它是Oracle系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是2,以此类推,这个伪字段可以用于限制查询返回的总行数,而且rownum不能以任何表的名称作为前缀。
如以下语句将无法正常运行:
select student.*, student.rownum from student;
我们如果要将rownum这个伪字段动态产生的列显示出来,需要使用如下语句:
select t.*, rownum from student t;
如果我们在查询时加入了限制条件,则rownum又将动态生成。结论就是rownum是不会与任何一行进行绑定都是根据查询后的记录来生成的:
select t.*, rownum from student t where sage > 25;
由于rownum的特殊性,我们在使用rownum时必须注意以下事项:
select * from student where rownum = 1; -- 能查询到第一条记录 select * from student where rownum = 2; -- 不能查询第二条记录
select * from student where rownum > 2; -- 不能查询出记录
select * from student where rownum < 3; -- 选择前两条记录
-- 正常返回最后三条记录 select * from student where rownum < 4 order by sid desc; -- 返回了前三条记录 select * from student where rownum < 4 order by sage desc;
我们可以看到,同样的sql语句,只是排列序不一样,就导致了完全不一样的结果。两个语句的对比中可以看出在第二条语句中rownum并不是以SAGE列生成序列号,而是在插入记录时以主键列为参考生成的。之所以我们在使用第一条语句时可以成功取得最后三条,原因就在于第一条语句是按照主键进行排序的。
select * from (select * from student order by sage desc) where rownum < 4;
select * from student where rownum < 20 minus -- 将两个记录集相减 select * from student where rownum < 10;
或者
select * from (select rownum r, student.* from student where rownum < 20 order by sid) where r >= 10;
select student.*, rowid from student;
原文:https://www.cnblogs.com/xiaogongjin/p/11828562.html