替代二级嵌套相关子查询

时间:2017-05-04 10:20:32

标签: sql oracle oracle11g

我需要替代以下SQL查询。原因是某些早期版本的Oracle数据库(在12C之前,不确定究竟是哪一个)不支持Oracle 12C所在的第二级嵌套相关子查询。

select 
    a.val1,
    a.val2,
    (
        select /* select the top single-field record from the inner select 
                statement */
            * 
        from 
        (
            select 
                b.val1
            from 
                tb2 b
            where 
                b.val2 < a.val3 and b.val3 = a.val4
            order by 
                b.val2 desc /* order by b.val2 desc in order to allow 
                                the outer select statement to obtain the 
                                largest b.val2 value */
        ) 
        where rownum = 1
    ) as someName
from
    tb1 a;

2 个答案:

答案 0 :(得分:4)

您可以使用keep

执行此操作
select a.val1, a.val2,
       (select max(b.val1) keep (dense_rank first order by val2 desc)
        from tb2 b
        where b.val2 < a.val3 and b.val3 = a.val4
       ) as someName
from tb1 a;

keep是Oracle中强大的语法,documentation对此进行了解释。从本质上讲,这会根据val1的排序获得val2的第一个值。这与first_value(val1) over (order by val2 desc)的作用非常相似 - 除了keep充当聚合函数。

答案 1 :(得分:0)


您可以使用以下查询

select a.val1, a.val2, b.val1 from tb1 a
inner join
tb2 b on (b.val2 < a.val3 and b.val3 = a.val4) 
order by b.val2 desc;

 select a.val1, a.val2, b.val1 from tb1 a
inner join
(select val1 from tb2) b on (b.val2 < a.val3 and b.val3 = a.val4)
order by b.val2 desc;

如果您遇到任何问题,请告诉我