考虑table1和table2具有一对多关系(table1是主表,table2是详细信息表).我想从table1获取记录,其中某些值('XXX')是与table1相关的详细记录的table2中最新记录的值.我想要做的是:
select t1.pk_id
from table1 t1
where 'XXX' = (select a_col
from ( select a_col
from table2 t2
where t2.fk_id = t1.pk_id
order by t2.date_col desc)
where rownum = 1)
Run Code Online (Sandbox Code Playgroud)
但是,因为相关子查询中对table1(t1)的引用是两级深度,所以它会弹出Oracle错误(无效的id t1).我需要能够重写这个,但有一点需要注意,只有where子句可以改变(即初始select和from必须保持不变).可以吗?
这是一种不同的分析方法:
select t1.pk_id
from table1 t1
where 'XXX' = (select distinct first_value(t2.a_col)
over (order by t2.date_col desc)
from table2 t2
where t2.fk_id = t1.pk_id)
Run Code Online (Sandbox Code Playgroud)
以下是使用排名功能的相同想法:
select t1.pk_id
from table1 t1
where 'XXX' = (select max(t2.a_col) keep
(dense_rank first order by t2.date_col desc)
from table2 t2
where t2.fk_id = t1.pk_id)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5819 次 |
最近记录: |