考虑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)
但是,因为相关子查询中对table1(t1)的引用是两级深度的,所以它会弹出一个Oracle错误(无效的id t1)。我需要能够重写这个,但有一点需要注意,只有where子句可以改变(即初始select和from必须保持不变)。可以吗?
答案 0 :(得分:6)
这是一种不同的分析方法:
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)
以下是使用排名功能的相同想法:
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)
答案 1 :(得分:3)
你可以在这里使用分析:将table1连接到table2,获取table1中每个元素的最新table2记录,并验证这个最新元素的值是否为'XXX':
SELECT *
FROM (SELECT t1.*,
t2.a_col,
row_number() over (PARTITION BY t1.pk
ORDER BY t2.date_col DESC) rnk
FROM table1 t1
JOIN table2 t2 ON t2.fk_id = t1.pk_id)
WHERE rnk = 1
AND a_col = 'XXX'
更新:无需修改顶级SELECT,您可以编写如下查询:
SELECT t1.pk_id
FROM table1 t1
WHERE 'XXX' =
(SELECT a_col
FROM (SELECT a_col,
t2_in.fk_id,
row_number() over(PARTITION BY t2_in.fk_id
ORDER BY t2_in.date_col DESC) rnk
FROM table2 t2_in) t2
WHERE rnk = 1
AND t2.fk_id = t1.pk_id)
基本上你只加入(SEMI-JOIN)table2中每行最fk_id
答案 2 :(得分:-1)
试试这个:
select t1.pk_id
from table1 t1
where 'XXX' =
(select a_col
from table2 t2
where t2.fk_id = t1.pk_id
and t2.date_col =
(select max(t3.date_col)
from table2 t3
where t3.fk_id = t2.fk_id)
)
答案 3 :(得分:-1)
这是否符合您的要求?
select t1.pk_id
from table1 t1
where 'XXX' = ( select a_col
from table2 t2
where t2.fk_id = t1.pk_id
t2.date_col = (select max(date_col) from table2 where fk_id = t1.pk_id)
)