检索rownum的有效机制

时间:2011-11-08 10:11:51

标签: oracle

这里很快。所以我读到网络上的rownum,我正试图看到 哪种方式调用它是最好的,因为基于SQL Optimizer两种方法都显示了 没有区别。

select count(distinct BCC || '~' || BN) BCCN 
from LINK_TBL 
where AN = 'abcdefg' 
and BR = 1 
and rownum <= 5;

select count(distinct BCCN)
from (
select BCC||'~'|| BN BCCN 
from LINK_TBL 
where AN = 'abcdefg' and BR = '1'
)
where rownum <= 5;

2 个答案:

答案 0 :(得分:5)

优化器可以选择在其认为合适的情况下解析/重新组织您的查询,只要它提供正确的结果即可。如果您查看解释计划,您可能会发现它们完全相同。

答案 1 :(得分:1)

我怀疑您在使用order by时使用rownum的重要性。您发布的两个查询在功能上是等效的。但是,以下两个查询不是:

select count(distinct BCC || '~' || BN) BCCN 
from LINK_TBL 
where AN = 'abcdefg' 
and BR = 1 
and rownum <= 5
order by BCC || '~' || BN;

select count(distinct BCCN)
from (
select BCC||'~'|| BN BCCN 
from LINK_TBL 
where AN = 'abcdefg' and BR = '1'
order by BCC || '~' || BN
)
where rownum <= 5;

不同之处在于,第一个查询以指定顺序获取所有行,然后获取前5行,第二个查询获取5行,然后仅排序5行。