gpt4 book ai didi

sql - 从 SQL 查询 Oracle 中获取记录范围

转载 作者:行者123 更新时间:2023-12-05 00:28:19 27 4
gpt4 key购买 nike

我想使用此 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
)
/

祝福

最佳答案

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

关于sql - 从 SQL 查询 Oracle 中获取记录范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10091506/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com