Oracle分布查询用三层嵌套 步骤如下:
--第三层:分页过滤
select b.* from(
--第二层:给定行号
select rownum r,a.*from(
第一层:排序
select * from 表 order by 字段
)a
where rownum<=最大行
)b where b.r between 最小行 and 最大行
关键点:先排序,后给行号,两个步骤要分开!
为了程序的通用性,对任意数据集都能分页,利用子查询改为如下结构:
--第三层:分页过滤
select b.* from(
--第二层:排序
select rownum r,a.* from(
--第一层:排序
select * from (一个已经排序的数据集)
)a where rownum<=最大行
)b where b.r between 最小行 and 最大行
如上面的查询改为:
--第三层:分页过滤
select b.* from(
--第二层:给定行号
select rownum r,a.* from (
--第一层:排序
select * from (select t.* from t_stu order by s_birthday desc)
)a where rownum<=最大行
)b where b.r between 最小行 and 最大行
或者其他查询语句:
--第三层:分页过滤
select b.* from(
--第二层:给定行号
select rownum r,a.* from(
--第一层:排序
select * from (select t.* from 新闻表 t order by 日期 desc)
)a where rownum<=最大行
)b where b.r between 最小行 and 最大行
也可以使用解析函数完成上面相同的任务,步骤简单:
select * from (
select row_number() over (order by s_birthday desc) as r, t.* from t_stu t
) where r between 2 and 4
select * from ( select row_.*, rownum rownum_ from (
select * from 表名 (where条件略)
) row_ where 最大行数 >= rownum )
where rownum_ > 最小行数
用这种方式,注意
最大行数=pageNo * pageSize
最小行数= (pageNo - 1) * pageSize+1
第一页查询 0-10
第二页查询 11-20
第三页查询 21-30
……
最小行数= (pageNo - 1) * pageSize
不需要+1,因为是>不是>=