我正在编写一个查询,它在 select 语句中嵌套了查询,如下所示。
Select t1.R1,
(
select * from
(
select t2.R2
from table2 t2
where t2.Condition_1=t1.C1
order by t2.Condition_2 desc
)
where rownum=1
),
t1.R3
from table1 t1
我正在尝试将主查询对象传递到 select 语句中的子查询内的子查询中。
当我执行这个时,我在
t1.C1
处收到对象无效错误.我能够传递主表的对象
table1
到第一个子查询,但如何传递 table1
子查询中的子查询列?在这种情况下,有人可以帮助我吗?
最佳答案
您只能引用低至一级子查询的对象,因此在内部子查询中无法识别 t1
。
有几种方法可以做到这一点。坚持使用当前的子查询,您可以将其设为内嵌 View 并加入其中:
select t1.r1, t2.r2, t1.r3
from table1 t1
join (
select *
from (
select condition_1, r2
from table2
order by condition_2 desc
)
where rownum = 1
) t2 on t2.condition_1 = t1.c1;
子查询根据您的排序条件为每个
table2
找到一个 condition_1
记录;然后该单行可以从 table1
连接到单行(假设 c1
是唯一的)。或者您可以使用分析函数:
select r1, r2, r3
from (
select t1.r1, t2.r2, t1.r3,
row_number() over (partition by t2.condition_1
order by t2.condition_2 desc) as rn
from table1 t1
join table2 t2 on t2.condition_1 = t1.c1
)
where rn = 1;
这将连接两个表,然后根据分析函数的窗口子句中的排序条件,通过查看已连接的结果集来决定保留
table2
中的哪些值。单独运行的内部查询会产生您之前尝试加入时看到的内容,包含所有“重复项”(结果集中并不是真正的重复项,而是来自 r1
的每个 r3
/table1
对的多行),并添加rn
列对这些重复项中的结果集行进行排名;然后外部查询将其过滤为仅显示排名第一的行。SQL Fiddle demo of both approaches。
如果
condition_2
不是唯一的,那么您需要决定如何处理关系 - 如果 table2
对于相同的 r2
和 condition_1
组合可以有两个 condition_2
值。在这种情况下,您可以查看不同的分析函数 - 例如 rank
。
关于oracle - 如何将主查询列传递给嵌套子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861394/