You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle中如何从数据表中间取数?rownum查询结果不符预期

Oracle 从数据表中间获取数据的解决方案

问题原因

你遇到的问题源于Oracle rownum的特性:rownum是在结果集生成时逐行分配的序号,只有当行被查询引擎选中时才会依次分配1、2、3...。当直接用where rownum between 5000 and 9857时,第一行的rownum为1,不满足>=5000的条件被过滤;第二行依然会被分配rownum=1,同样不满足条件,最终没有行被选中,所以count结果为0。

解决方案

方法1:子查询预分配rownum

先通过子查询为每一行分配rownum,再在外层筛选目标范围:

select count(1)
from (
    select t.*, rownum as rn
    from time_day_dm t
)
where rn between 5000 and 9857;

如果需要结果顺序稳定(避免每次查询rownum分配顺序变化),建议在子查询中添加order by:

select count(1)
from (
    select t.*, rownum as rn
    from (
        select * from time_day_dm order by 你的排序字段 -- 替换为实际排序列
    ) t
)
where rn between 5000 and 9857;

方法2:使用ROW_NUMBER()窗口函数

窗口函数可以更灵活地生成行号,同样建议配合order by保证顺序一致性:

select count(1)
from (
    select *, row_number() over(order by 你的排序字段) as rn
    from time_day_dm
)
where rn between 5000 and 9857;

方法3:Oracle 12c+ 专用OFFSET/FETCH语法

如果你的Oracle版本是12c或更高,可使用更简洁的语法直接跳过指定行数并获取目标数据:

select count(1)
from (
    select * from time_day_dm
    order by 你的排序字段
    offset 4999 rows -- 跳过前4999行,从第5000行开始
    fetch next 4857 rows only -- 取4857行(9857-5000+1=4857)
);

内容的提问来源于stack exchange,提问作者yhmirr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:55:43