我正在使用更新查询,其中在嵌套子查询中使用外部变量,但是发现错误:
SQL错误:ORA-00904:“ FS”。“ GR_NUMBER”:无效的标识符
update table fs set fs.branch_id=
(select branch_id
from
(select branch_id,row_number() over(PARTITION by gr_number order by updated_ts desc) as Sno
from admission_log
where gr_number=fs.gr_number )
where sno=1) ;
答案 0 :(得分:1)
查询的问题在于,您正在尝试访问下两级的子查询中的fs.gr_number
列。您只能访问下一级的子查询中的顶级列。
您的声明应为:
UPDATE fs
SET fs.branch_id = (SELECT branch_id
FROM (SELECT branch_id,
gr_number,
row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts DESC) AS sno
FROM admission_log) x
WHERE x.gr_number = fs.gr_number
AND sno = 1);
将相关性向下移动一级。请注意,我还如何为嵌套的子查询加上别名。
性能不应该太差,因为x.gr_number = fs.gr_number
谓词涉及子查询中分析功能所在的同一列。这应该允许Oracle适当地过滤子查询。
ETA:您也可以改用MERGE语句:
MERGE INTO fs tgt
USING (SELECT branch_id,
row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts DESC) AS sno
FROM admission_log) src
ON (tgt.gr_number = src.gr_number AND src.sno = 1)
WHEN MATCHED THEN
UPDATE tgt.branch_id = src.branch_id;
答案 1 :(得分:0)
使用此代码:
update fs a
set a.branch_id =
(select c.branch_id
from (select b.branch_id,
row_number() over(PARTITION by b.gr_number order by b.updated_ts desc) as Sno
from admission_log b
where b.gr_number = a.gr_number) c
where c.sno = 1);
答案 2 :(得分:-1)
由于它是Oracle,因此可以使用merge子句并使用min()函数而不是row_number()函数来获取值。
merge into table fs using
(select gr_number, min(branch_id) as branch_id from admission_log) qry
on
(fx.gr_number = qry.gr_number)
when matched then
update
set
fs.branch_id = qry.branch_id;
如果您仍然想使用roe_number()函数,则查询如下。您要加入表格的WHERE子句应在子查询之外。
update table fs set fs.branch_id=
(select branch_id
from
(select branch_id,row_number() over(PARTITION by gr_number order by updated_ts desc)
as Sno
from admission_log)
where sno=1
and gr_number=fs.gr_number) ;