【问题标题】:How to update based on subquery?如何根据子查询进行更新?
【发布时间】:2021-05-01 02:32:35
【问题描述】:

我有两张桌子:

Product
Id
Code
Value
Info
Id
Serial
Description

现在我想用表 Info 中的 Serial 的值更新表 Product 中的每一列 Code。我的 where 条件很方便,因为我所有的 Product codes 目前都是来自 InfoId

这就是我正在尝试的:

update Product P set
P.Code = (select Serial from Info where id = P.Code);

在这里我得到了错误:ORA-01427: single-row subquery returns more than one row。 我觉得我错过了另一个 where 子句,但我不确定该放在哪里?

【问题讨论】:

  • 我们不知道,你当前条件下的子查询返回多行,只有子查询返回且只返回一行时才能这样做。所以这只适用于一对一的关系,显然info.idproduct.code 不是一对一的。
  • 什么条件只能给你一行?只有拥有数据的你才能知道。
  • 该错误意味着您在 Info 表中有多个具有相同 id 的记录。尝试 select id, count(1) from info group by id order by 1 desc;找到那些 id

标签: sql oracle sql-update


【解决方案1】:

您的子查询返回多个结果(如错误所示)。 例如,您可以使用如下聚合函数来限制更新的行数:

update Product P set P.Code = (select MAX(Serial) from Info where id = P.Code);

【讨论】:

  • 最接近我需要的答案。在你给我看之前,我没有把它限制在一行,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多