从SQL查询Oracle获取记录范围

时间:2012-04-10 15:18:19

标签: sql oracle oracle10g oracle11g

我想使用此SQL查询仅获取8到10之间的记录:

select *
from(
SELECT a.*,rownum rn 
FROM ACTIVESESSIONSLOG  a
ORDER BY USERID ASC)
WHERE rn  >= 8 and rn <= 10

当我将这个SQL查询实现到分页中时,无论我配置多少行显示在页面中,我每次都会在第二页上获得1行。这个SQL查询有效吗?

这是表结构:

-- TABLE ACTIVESESSIONSLOG

CREATE TABLE ACTIVESESSIONSLOG(
  ASESSIONID VARCHAR2(30 ) NOT NULL,
  USERID VARCHAR2(30 ),
  ACTIVITYSTART TIMESTAMP(6),
  ACTIVITYEND TIMESTAMP(6),
  ACTIVITY CLOB
)
/

祝福

1 个答案:

答案 0 :(得分:4)

rownumORDER BY之前应用,因此您的查询几乎肯定不会达到预期效果。您的查询实质上是要求任意3行,ORDER BY没有做任何有用的事情。

您可以使用分析函数row_number代替,即

SELECT *
  FROM (SELECT a.*,
               row_number() over (order by userid asc) rn
          FROM activeSessionsLog a)
 WHERE rn BETWEEN 8 AND 10

将翻阅结果

SQL> ed
Wrote file afiedt.buf

  1  select empno, ename, job
  2    from (select e.*,
  3                 row_number() over (order by empno) rn
  4            from emp e)
  5*  where rn between 1 and 3
SQL> /

     EMPNO ENAME      JOB
---------- ---------- ---------
      7369 SMITH      CLERK
      7499 ALLEN      SALESMAN
      7521 WARD       SALESMAN

SQL> ed
Wrote file afiedt.buf

  1  select empno, ename, job
  2    from (select e.*,
  3                 row_number() over (order by empno) rn
  4            from emp e)
  5*  where rn between 4 and 8
SQL> /

     EMPNO ENAME      JOB
---------- ---------- ---------
      7566 JONES      MANAGER
      7654 MARTIN     SALESMAN
      7698 BLAKE      MANAGER
      7782 CLARK      MANAGER
      7788 SCOTT      ANALYST

SQL> ed
Wrote file afiedt.buf

  1  select empno, ename, job
  2    from (select e.*,
  3                 row_number() over (order by empno) rn
  4            from emp e)
  5*  where rn between 9 and 11
SQL> /

     EMPNO ENAME      JOB
---------- ---------- ---------
      7839 KING       PRESIDENT
      7844 TURNER     SALESMAN
      7876 ADAMS      CLERK

但是,做这样的事情可能更有效率,Oracle可以使用内部rownum <= 10谓词来知道一旦识别出前10行就可以停止对数据进行排序。

SELECT c.*
  FROM (SELECT b.*, rownum rn
          FROM (SELECT a.*
                  FROM activeSessionsLog a
                 ORDER BY userid asc) b
         WHERE rownum <= 10) c
 WHERE rn >= 8