`
elitesunry
  • 浏览: 36280 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Oracle rownum

阅读更多

create table student (ID char(6), name VARCHAR2(100));
insert into student values('200001','张一');
insert into student values('200002','王二');
insert into student values('200003','李三');
insert into student values('200004','赵四');
insert into student values('200005','赵6');
insert into student values('200006','赵5');
------------------------------------------------------
select * from student where rownum=1;-- 可以
select * from student where rownum=2;-- 不可以(rownum = n为false,其中 n > 1)

select * from student where rownum>1;-- 不可以
select * from student where rownum>2;-- 不可以(rownum > n为false, 其中 n任意)

select * from student where rownum<3;-- 可以
select * from student where rownum<0;-- 可以(rownum < n为true,其中 n任意)
------------------------------------------------------
select * from 
(
   select rownum no,id,name from student where rownum<=3 
)
where no >=2;-- 数据量大时有效率问题

select rownum, t.* from student t order by t.name;--(1)
select rownum, t.* from student t;--(2)
-- 以上两行可以看出,rownum为插入时的顺序编号

-- 自然而然,先取出有序的结果集再次在新表上作用rownum就能获得要的结果(可以理解为插入虚表时的顺序编号么?^_^)
select v.*, rownum
from
(
select * from student order by name
)v;

-- 有人认为给name加上索引或者主键,便可以打乱表数据原来插入顺序(即rownum)以新的方式排序以获得新的rownum
create index idx_name on STUDENT (name);
-- 并没有变化,删除索引上主键
drop index IDX_NAME;
alter table STUDENT add constraint key_name primary key (NAME);
-- 结果证明有效,(1)(2)两句都按照1-6的rownum名字顺序分别为插入顺序和字幕顺序
alter table STUDENT drop constraint KEY_NAME cascade;
-- 去掉主键,验证又恢复了初始状态,再来看看主键的问题,这次创建唯一主键
create unique index inx_name on STUDENT (name);
-- 唯一主键依然无效,删除。试验完毕
drop index INX_NAME;

 到此,对于oracle分页排序,排序取若干行数据等问题基本就清楚了,至于为什么加索引不能达到预期目的的理由是什么,还需要进一步学习。

 

参考资料:http://www.cnblogs.com/temptation/archive/2007/05/16/748897.html

1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics