【问题标题】:Update column in Oracle table with value from another table with duplicates用另一个表中的重复值更新 Oracle 表中的列
【发布时间】:2020-11-13 18:34:15
【问题描述】:

我正在尝试将表 A 中的列 (REPT_IND) 更新为表 B 中的值,其中 A.ID = B.ID 和表 B 中的某些条件。 表 B 中有一些重复项,但 REPT_IND 是相同的,我仍然需要该值。 我怎样才能在 Oracle 上做到这一点?感谢您的任何提示!

以下代码有错误:

ORA-01427: single-row subquery returns more than one row

代码:

UPDATE A
SET REPT_IND= (
                        SELECT B.REPT_IND
                        FROM  B
                        INNER JOIN A
                            ON B.ID = A.ID
                        where A.ID = B.ID
                        and B.job_type = 'P'
                        and B.FT_PT is not null
                        );

【问题讨论】:

  • 如果B中没有满足您条件的行,您是否要将REPT_IND设置为null?
  • 是的@SayanMalakshinov

标签: sql oracle join sql-update subquery


【解决方案1】:

你也可以试试merge声明:

merge into a 
using (
    select a.id,max(b.rept_ind) rept_ind
    from  a left join b on a.id=b.id
    where b.job_type = 'p'
      and b.ft_pt is not null
) b
on (a.id=b.id)
when matched then update 
    set a.rept_ind=b.rept_ind;

或者如果 b 中没有相关行,您不想将 a.rept_ind 设置为 null:

merge into a 
using (
    select b.id, max(b.rept_ind) rept_ind
    from  b
    where 
            b.job_type = 'p'
        and b.ft_pt is not null
    group by b.id
) b
on (a.id=b.id)
when matched then update 
    set a.rept_ind=b.rept_ind;

【讨论】:

  • 这个运行没有错误,但它没有更新任何行
  • 你是怎么检查的?此查询返回什么:select count(distinct b.id) c from b where b.job_type = 'p' and b.ft_pt is not null and exists(select 1 from a where a.id=b.id)
  • @Anderson 您确定 B 中的行与您的条件相关吗?
  • 我运行了上面的查询,得到了 35k 行
  • @Anderson 好的,所以合并应该已经更新了这 35k 行。您如何检查更新的行数?
【解决方案2】:

考虑:

update a
set rept_ind= (
    select max(b.rept_ind)
    from  b
    where 
        a.id = b.id
        and b.job_type = 'p'
        and b.ft_pt is not null
);

没有必要在子查询中再次join 表a - 一个相关子句就足够了。并且您可以通过打开聚合来解决可能的重复问题,这可以保证只返回一行。

您也可以在子查询中使用select distinct 代替select max(...)。这在某种程度上更准确,因为它确实确保多行具有相同的 rept_ind(如果它们没有,那么您仍然会收到 ORA-01427 错误)。

【讨论】:

  • 这已经运行了大约 15 分钟,到目前为止没有任何错误,它将更新大约 35k 行...这是正常的吗? (我连接到数据库非常好)或者这可能是查询的问题吗? @gmb
  • @Anderson:考虑在b(id, type, ft_pt) 上建立索引以加快查询速度。
【解决方案3】:

只需使用相关子查询。 . .并且不要在子查询中重复表引用:

UPDATE A
    SET REPT_IND = (SELECT B.REPT_IND
                    FROM  B
                    WHERE B.ID = A.ID AND
                          B.job_type = 'P' AND
                          B.FT_PT is not null AND
                          rownum = 1
                   );

【讨论】:

  • 这看起来很干净,谢谢.. 但我仍然得到:ORA-01427:单行子查询返回不止一行
  • @Anderson 。 . .这似乎是您的数据模型中的一个缺陷——您有多个匹配的行。您的选择是聚合或添加rownum = 1。我将后者添加到答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多