sql—使用另一个表中的值更新oracle表中的列,该表中的值重复

1tuwyuhd  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(400)

我正在尝试将表a中的列(rept\u ind)更新为表b中的值,其中a.id=b.id和表b中的某些条件。表b中有一些重复项,但是rept\u ind是相同的,我仍然需要该值。如何在oracle上执行此操作?任何提示都很感激谢谢!
以下代码有错误:

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

代码:

  1. UPDATE A
  2. SET REPT_IND= (
  3. SELECT B.REPT_IND
  4. FROM B
  5. INNER JOIN A
  6. ON B.ID = A.ID
  7. where A.ID = B.ID
  8. and B.job_type = 'P'
  9. and B.FT_PT is not null
  10. );
n3ipq98p

n3ipq98p1#

你也可以试试 merge 声明:

  1. merge into a
  2. using (
  3. select a.id,max(b.rept_ind) rept_ind
  4. from a left join b on a.id=b.id
  5. where b.job_type = 'p'
  6. and b.ft_pt is not null
  7. ) b
  8. on (a.id=b.id)
  9. when matched then update
  10. set a.rept_ind=b.rept_ind;

或者如果您不想将a.rept\u ind设置为null(如果b中没有相关行):

  1. merge into a
  2. using (
  3. select b.id, max(b.rept_ind) rept_ind
  4. from b
  5. where
  6. b.job_type = 'p'
  7. and b.ft_pt is not null
  8. group by b.id
  9. ) b
  10. on (a.id=b.id)
  11. when matched then update
  12. set a.rept_ind=b.rept_ind;
展开查看全部
iibxawm4

iibxawm42#

考虑:

  1. update a
  2. set rept_ind= (
  3. select max(b.rept_ind)
  4. from b
  5. where
  6. a.id = b.id
  7. and b.job_type = 'p'
  8. and b.ft_pt is not null
  9. );

没有必要这么做 joina 同样在子查询中-一个correlation子句就足够了。您还可以通过启用聚合来解决可能的重复,聚合保证只返回一行。
你也可以用 select distinct 而不是 select max(...) 在子查询中。这在某种程度上更准确,因为它确实确保了多行具有相同的属性 rept_ind (如果他们没有,那么你仍然会得到 ORA-01427 错误)。

kuhbmx9i

kuhbmx9i3#

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

  1. UPDATE A
  2. SET REPT_IND = (SELECT B.REPT_IND
  3. FROM B
  4. WHERE B.ID = A.ID AND
  5. B.job_type = 'P' AND
  6. B.FT_PT is not null AND
  7. rownum = 1
  8. );

相关问题