3

I want to use this SQL query to get only the records between 8 and 10:

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

When I implement this SQL query into pagination I get every time 1 row on the second page no matter how many rows I have configured to be displayed into the pages. Is this SQL query valid?

This is the table structure:

-- TABLE ACTIVESESSIONSLOG

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

Best wishes

4

2 回答 2

4

rownum在 the 之前应用,ORDER 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
于 2012-04-10T15:35:27.030 回答
1

从 Oracle 12c 开始,您现在可以使用 offset/fetch 子句。

您现在可以编写如下查询:

SELECT *
FROM user_objects
ORDER object_name
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY

请查看此新功能并考虑执行计划中的改进。

于 2017-05-18T09:27:50.263 回答