6

有没有办法可以减少下面内部查询的 OVER 部分中的“ORDER BY lro_pid”子句的影响?

SELECT *
  FROM (SELECT a.*, 
               Row_Number() over (PARTITION BY search_point_type 
                                      ORDER BY lro_pid) spt_rank
          FROM lro_search_point a
      ORDER BY spt_rank)
 WHERE spt_rank = 1;

我不在乎在分区中排序这个结果,因为我想完全按不同的变量排序。lro_pid 是一个索引列,但这似乎仍然像目前一样浪费资源。(也许有一种方法可以将排序限制在单行的范围内??希望根本不会花费时间/精力在分区内进行排序)

4

3 回答 3

6

有几件事可以尝试:

你可以ORDER BY 'constant'在 OVER 子句中吗?

如果不允许按常量排序,那又如何ORDER BY (lro_pid * 0)呢?

我不是 Oracle 专家(MSSQL 更适合我) - 因此有问题要回答您的问题!

于 2011-06-02T22:28:54.753 回答
5

正如@Will A 所建议的那样,在分析 ORDER BY 中使用常量似乎是最快的方法。优化器仍然执行排序,但它比对列进行排序要快。此外,您可能希望删除第二个 ORDER BY,或者至少将其移至外部查询。

下面是我的测试用例:

--Create table, index, and dummy data.
create table lro_search_point(search_point_type number, lro_pid number, column1 number
    ,column2 number, column3 number);
create index lro_search_point_idx on lro_search_point(lro_pid);
insert /*+ append */ into lro_search_point
select mod(level, 10), level, level, level, level from dual connect by level <= 100000;
commit;


--Original version.  Averages 0.53 seconds.
SELECT * FROM 
(
    SELECT a.*, Row_Number() over (PARTITION BY search_point_type ORDER BY lro_pid) spt_rank
    FROM lro_search_point a
    ORDER BY spt_rank
)
WHERE spt_rank=1;


--Sort by constant.  Averages 0.33 seconds.
--This query and the one above have the same explain plan, basically it's
--SELECT/VIEW/SORT ORDER BY/WINDOW SORT PUSHED RANK/TABLE ACCESS FULL.
SELECT * FROM 
(
    SELECT a.*, Row_Number() over (PARTITION BY search_point_type ORDER BY -1) spt_rank
    FROM lro_search_point a
    ORDER BY spt_rank
)
WHERE spt_rank=1;


--Remove the ORDER BY (or at least move it to the outer query).  Averages 0.27 seconds.
SELECT * FROM 
(
    SELECT a.*, Row_Number() over (PARTITION BY search_point_type ORDER BY -1) spt_rank
    FROM lro_search_point a
)
WHERE spt_rank=1;


--Replace analytic with aggregate functions, averages 0.28 seconds.
--This idea is the whole reason I did this, but turns out it's no faster.  *sigh*
--Plan is SELECT/SORT GROUP BY/TABLE ACCESS FULL.
--Note I'm using KEEP instead of just regular MIN.
--I assume that you want the values from the same row.
SELECT a.search_point_type
    ,min(lro_pid) keep (dense_rank first order by -1)
    ,min(column1) keep (dense_rank first order by -1)
    ,min(column2) keep (dense_rank first order by -1)
    ,min(column3) keep (dense_rank first order by -1)
FROM lro_search_point a
group by a.search_point_type;
于 2011-06-03T05:59:37.480 回答
-1

要省略该子句ORDER BY,您可以使用ORDER BYrownum。

于 2012-02-07T06:39:59.377 回答