Oracle:ROW_NUMBER比ROWNUM快20倍

时间:2014-02-13 10:24:36

标签: sql database oracle oracle11g query-optimization

表详情:

  • table1有20百万条记录
  • table2有120个条目。

如果是,则返回这些请求的目标。条目数无关紧要。

有人解释原因吗

SELECT COUNT(rn) count
FROM
(
 SELECT ROW_NUMBER() OVER (order by t2.id_field) AS rn
 FROM table1 t1
 INNER JOIN table2 t2 ON t2.id_table2 = t1.id_table2
 WHERE t2.id_field = 2
)
WHERE rn < 2;

快20倍:

SELECT COUNT(rn) count
FROM
(
 SELECT 1 rn
 FROM table1 t1
 INNER JOIN table2 t2 ON t2.id_table2 = t1.id_table2
 WHERE t2.id_field = 2
)
WHERE ROWNUM < 2;

1 个答案:

答案 0 :(得分:1)

如前所述,ROW_NUMBER()和ROWNUM根本不相同。

第一个是使用窗口的分析函数。订单由命令指定。

http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm#SQLRF51198

select
  ename,
  ROW_NUMBER() OVER (order by ename ) AS rn 
from emp
where deptno =20;

ENAME              RN
---------- ----------
ADAMS               1
FORD                2
JONES               3
SCOTT               4
SMITH               5


Execution Plan
----------------------------------------------------------
Plan hash value: 3145491563

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      |     5 |    45 |     4  (25)| 00:00:01 |
|   1 |  WINDOW SORT       |      |     5 |    45 |     4  (25)| 00:00:01 |
|*  2 |   TABLE ACCESS FULL| EMP  |     5 |    45 |     3   (0)| 00:00:01 |
---------------------------------------------------------------------------

使用rownum:

select ename, 
  ROWNUM
from emp
where deptno =20;

ENAME          ROWNUM
---------- ----------
SMITH               1
JONES               2
SCOTT               3
ADAMS               4
FORD                5


Execution Plan
----------------------------------------------------------
Plan hash value: 1498225739

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      |     5 |    45 |     3   (0)| 00:00:01 |
|   1 |  COUNT             |      |       |       |            |          |
|*  2 |   TABLE ACCESS FULL| EMP  |     5 |    45 |     3   (0)| 00:00:01 |