使用 rownum 选择表格的第二行

2023-09-18数据库问题
3

本文介绍了使用 rownum 选择表格的第二行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我尝试了以下查询:

select empno from (
                   select empno 
                     from emp
                    order by sal desc
                  )
where rownum = 2

这不会返回任何记录.

当我尝试这个查询时

 select rownum,empno from (
                        select empno from emp order by sal desc) 

它给了我这个输出:

ROWNUM  EMPNO      
1       7802        
2       7809    
3       7813    
4       7823

谁能告诉我我的第一个查询有什么问题?为什么添加ROWNUM过滤器时不返回任何记录?

Can anyone tell me what's the problem with my first query? Why is it not returning any records when I add the ROWNUM filter?

推荐答案

为了解释这种行为,我们需要了解 Oracle 如何处理行号.给一行赋值 ROWNUM 时,Oracle 从 1 开始,仅在选择一行时增加值;也就是说,当所有WHERE 子句中的条件得到满足.由于我们的条件需要ROWNUM 大于 2,未选择任何行且 ROWNUM 为永远不会超过 1.

To explain this behaviour, we need to understand how Oracle processes ROWNUM. When assigning ROWNUM to a row, Oracle starts at 1 and only increments the value when a row is selected; that is, when all conditions in the WHERE clause are met. Since our condition requires that ROWNUM is greater than 2, no rows are selected and ROWNUM is never incremented beyond 1.

最重要的是,以下条件将作为预期.

The bottom line is that conditions such as the following will work as expected.

... WHERE rownum = 1;

.. WHERE rownum = 1;

... WHERE rownum <= 10;

.. WHERE rownum <= 10;

虽然具有这些条件的查询将始终返回零行.

While queries with these conditions will always return zero rows.

...WHERE rownum = 2;

.. WHERE rownum = 2;

... WHERE rownum > 10;

.. WHERE rownum > 10;

引自了解 Oracle rownum

您应该以这种方式修改您的查询以便工作:

You should modify you query in this way in order to work:

select empno
from
    (
    select empno, rownum as rn 
    from (
          select empno
          from emp
          order by sal desc
          )
    )
where rn=2;

EDIT:我已经更正了查询以获取 rownum after 由 sal desc 排序

EDIT: I've corrected the query to get the rownum after the order by sal desc

这篇关于使用 rownum 选择表格的第二行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12