甲骨文中rownum之谜 [英] Mystery of rownum in oracle

查看:93
本文介绍了甲骨文中rownum之谜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力获取基于rownum的数据.当我执行以下查询以获取基于rownum 1 to 4的结果时,则工作正常.

I am struggling to fetch the data based on rownum. When I execute the below query to get the results based rownum 1 to 4 then it is working fine.

  SELECT ROWNUM TOTAL,MI.* FROM (SELECT USER_ID,CUSTOMER_NAME FROM ELEC_AUTO_MERC 
  ORDER BY CREATION_DATE DESC ) MI WHERE ROWNUM BETWEEN 1 AND 4;

但是当我执行相同的查询以从rownum 2 to 4获取结果时,它不起作用,它不会返回任何内容.

But when I am executing same query to get result from rownum 2 to 4 then it is not working, it doesn't return anything.

  SELECT ROWNUM TOTAL,MI.* FROM (SELECT USER_ID,CUSTOMER_NAME FROM ELEC_AUTO_MERC 
  ORDER BY CREATION_DATE DESC ) MI WHERE ROWNUM BETWEEN 2 AND 4;

作为一种解决方法,当我再使用一条SELECT语句时,它可以正常工作,但是我认为仅对rownum多次使用SELECT并不是一个好方法.

As a workaround, when I use one more SELECT statement then it is working fine, but I don't think it is good approach to use SELECT multiple times only for rownum.

SELECT * FROM (SELECT ROWNUM TOTAL,MI.* FROM (SELECT USER_ID,CUSTOMER_NAME FROM ELEC_AUTO_MERC 
  ORDER BY CREATION_DATE DESC ) MI) WHERE TOTAL BETWEEN 2 AND 4;

您能帮我创建优化查询吗?

Can you please help me out to create optimize query?

推荐答案

ROWNUM很奇怪,因为它可以作为查询中条件的一部分进行评估-但是如果该行随后未能通过该过滤器,则ROWNUM为其分配的值可再次用于下一行.

ROWNUM is weird in that it can be evaluated as part of a condition in the query - but if the row then fails to pass that filter, the ROWNUM value that it was assigned becomes available to be used again for the next row.

此操作的一个重要作用是,如果使用排除ROWNUM值1的任何条件,则永远不会获得匹配项.针对此条件进行测试的第一行将是第1行;但随后它将无法通过测试,因此下一行将被视为第1行;等等.

One important effect of this is that if you use any condition that excludes a ROWNUM value of 1, you will never get a match. The first row to be tested against this condition will be row 1; but then it will fail the test, so the next row will then be considered row 1; and so on.

所以您的条件ROWNUM BETWEEN 2 AND 4永远不可能成立.

So your condition ROWNUM BETWEEN 2 AND 4 can never be true.

您找到的解决方法是传统方法.另一个方法是使用分析功能对行进行排名,然后根据排名进行过滤,例如:

The workaround you have found is the traditional one. Another would be to use an analytic function to rank the rows, then filter on the rank, e.g.:

SELECT MI.* FROM (
  SELECT USER_ID,CUSTOMER_NAME, RANK() OVER (ORDER BY CREATION_DATE DESC) AS the_rank
  FROM ELEC_AUTO_MERC 
  ) MI
WHERE the_rank BETWEEN 2 AND 4;

多个分析函数-RANK,DENSE_RANK和ROW_NUMBER-可用于此目的,并且会产生略有不同的结果,尤其是在存在联系的情况下.查看文档.

Several analytic functions - RANK, DENSE_RANK, and ROW_NUMBER - can be used for this purpose, and will produce slightly different results, especially if there are ties. Check out the docs.

这篇关于甲骨文中rownum之谜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆