欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

三种常用数据库(Oracle、MySQL、SQLServer)的分页之Oracle分页

程序员文章站 2022-05-31 17:25:51
...

环境 Oracle 11gR2 SQLPlus 问题 Oracle 分页 解决 --创建测试表SQL create table test 2 ( 3 id number primary key, 4 name varchar2(20) not null 5 );表已创建。--创建序列SQLSQL create sequence seq_wgb_test;序列已创建。--插入数据SQL insert into t

环境

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  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行。


运行效果截图

三种常用数据库(Oracle、MySQL、SQLServer)的分页之Oracle分页

小技巧

快速插入数据:

insert into test(id, name) select seq_wgb_test.nextval, name from test;

Oracle中复制数据和MySQLSQLServer不一致,这里要注意下,因为使用的自增方式不同。

总结语法

Oracle中分页是使用子查询和rownum

select t.*

from

(

select rownum sn,te.*

from tableName te

where rownum

)t

where t.sn > num * (page - 1);

--num:每页显示的行数

--page:第几页

对应于Web程序中分页类似:

select t.*

from

(

select rownum sn,te.*

from tableName te

where rownum

)t

where t.sn > num * (pageNow - 1);

--pageNow:当前第几页

--pageSize:每页显示的记录数

参考资料

http://blog.csdn.net/wentasy/article/details/8200512

http://blog.csdn.net/wentasy/article/details/8200561