如何使用update在嵌套子查询中使用外部查询变量

oyjwcjzk  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(306)

我正在使用一个更新查询,其中我在嵌套子查询中使用了一个外部变量,但我发现一个错误:
sql错误:ora-00904:“fs”。“gr\ U编号”:无效标识符

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) ;
wgx48brx

wgx48brx1#

查询的问题是您试图访问 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 predicate 在子查询中涉及分析函数正在其上分区的同一列。这应该允许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;
b0zn9rqh

b0zn9rqh2#

使用此代码:

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);
cuxqih21

cuxqih213#

因为它是oracle,所以可以使用merge子句并使用min()函数而不是row\ u 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\u 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) ;

相关问题