问题:
语句1:select * from (select * from emp ORDER BY deptno) a where rownum<10;
语句2: select * from (select rownum num,t.* from (select empno,sal from emp order by deptno) t) where num 10 and 20;
语句1和语句2中会有相同的记录。
原因:看了1的执行计划有“SORT ORDER BY STOPKE” ,查找文档知道该计划是不会再所有的数据都一起排序完再取结果的,而是
只要找出结果集中的按特定顺序的最前N条记录,一旦找出了这N条记录,就无需再对剩下的数据进行排序,而直接返回结果。
据说内部用的是类似快速排序的思想
解决: order by后面加一个唯一标示如
select * from (select * from emp ORDER BY deptno,empno) a where rownum<10;
或者
select * from (select rownum num,t.* from (select empno,sal from emp order by deptno) t) where num<10;