select t2.* from --两层嵌套 (select t.* , rownum as row_numfrom t where rownum <=20) t2 where t2.row_num > 11
select t3.* from ( --三层嵌套 select t2.*, rownum as row_num from ( select * from t ) t2 where rownum<=20 ) t3 where t2.row_num>11
两层嵌套 ==三层嵌套???
1 select t2.* from (
2 select t.*, rownum as row_num from t where rownum<=20 order by ID asc
3 ) t2 where t2.row_num>10
45 order by ID asc
因为在查询的时候,order by 的执行是在 select 之后的,所以在第一层查询中,得到的结果可能是如下
这样的子结果集,在经过第二层过滤的时候,是得不到我们想要的结果的
所以需要用如下的sql语句实现分页排序
1 select t3.* from (
2 select t2.*, rownum as row_num from (
3 select * from t order by t.id asc
4 ) t2 where rownum<=20
5) t3
6 where t2.row_num>11
7 order by t3.id asc
SELECT *
FROM (SELECT *
FROM (SELECT ROWNUM AS ROW_ID, ORDER_ID
FROM ORDERS
ORDER BY ORDER_ID DESC) A
WHERE ROW_ID < 10)
WHERE ROW_ID >= 5;
--上面这样写也是错误的,正如前面的原因,有order by 和rownum时,先给rownum赋值,然后再对结果进行order by,
所以上面的语句同样是取rownum为5--10之间的记录,而不是排好序之后的5--10记录。
正确写法:
SELECT B.ORDER_ID,B.ORDER_DETAILS,B.R_ID
FROM (SELECT A.ORDER_ID,A.ORDER_DETAILS,ROWNUM AS R_ID --对排序好的结果取其rownum,再取rownum 小于给定值的记录(不能直接对rownum取大于)
FROM (SELECT ORDER_ID,ORDER_DETAILS --获取排序好的结果集
FROM ORDERS
ORDER BY ORDER_ID DESC) A
WHERE ROWNUM < 10) B
WHERE R_ID >= 5; --取R_ID大于给定值的记录