环境
Oracle 11gR2 + SQLPlus
问题
Oracle分页
解决
--创建测试表
SQL> create table test
2 (
3 id number primary key,
4 name varchar2(20) not null
5 );
表已创建。
--创建序列
SQL>
SQL> create sequence seq_wgb_test;
序列已创建。
--插入数据
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test1');
已创建 1 行。
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test2');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test3');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test4');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test5');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test6');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test7');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test8');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test9');
已创建 1 行。
SQL>
SQL> insert into test(id, name) values(seq_wgb_test.nextval, 'test10');
已创建 1 行。
SQL> insert into test(id, name) select seq_wgb_test.nextval, name from test;
已创建10行。
SQL> insert into test(id, name) select seq_wgb_test.nextval, name from test;
已创建20行。
SQL> insert into test(id, name) select seq_wgb_test.nextval, name from test;
已创建40行。
--执行分页
SQL> select t.*
2 from
3 (
4 select rownum sn,te.*
5 from test te
6 where rownum <= 10
7 )t
8 where t.sn > 0;
SN ID NAME
---------- ---------- --------------------
1 2 test1
2 3 test2
3 4 test3
4 5 test4
5 6 test5
6 7 test6
7 8 test7
8 9 test8
9 10 test9
10 11 test10
已选择10行。
运行效果截图
小技巧
快速插入数据:
insert into test(id, name) select seq_wgb_test.nextval, name from test;
Oracle中复制数据和MySQL、SQLServer不一致,这里要注意下,因为使用的自增方式不同。
总结语法
Oracle中分页是使用子查询和rownum。
select t.*
from
(
select rownum sn,te.*
from tableName te
where rownum <= num * page
)t
where t.sn > num * (page - 1);
--num:每页显示的行数
--page:第几页
对应于Web程序中分页类似:
select t.*
from
(
select rownum sn,te.*
from tableName te
where rownum <= pageSize * pageNow
)t
where t.sn > num * (pageNow - 1);
--pageNow:当前第几页
--pageSize:每页显示的记录数
参考资料
http://blog.youkuaiyun.com/wentasy/article/details/8200512
http://blog.youkuaiyun.com/wentasy/article/details/8200561