oracle真分页中的排序问题,
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;
--上面这样写是错误的。
正确写法:
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;
为什么上面是错的 ,而第二个加了别名就是正确的。
------解决方案--------------------那不是加了别名的问题,那是多了一次中间查询的问题。
------解决方案--------------------在一次查询中,既排序,又去伪列(ROWNUM),肯定是不对的。你可以看看ROWNUM中的序号是不是对的了
------解决方案--------------------换个位置试试
SQL code
select *
from (select t1.*,rownum rn
from (select ORDER_ID
from ORDERS
ORDER BY ORDER_ID DESC
) t1
where rownum <10
)
where rn>=5
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;