【问题标题】:Update statement with unmatched condition条件不匹配的更新语句
【发布时间】:2017-03-11 10:55:53
【问题描述】:

我有一个更新查询如下-

udate table1 tbl_out
set column1 =
    (select colValue from table1 t1, table2 t2
    where table1.product_id = table2.product_id
    and t1.id = tbl_out.id)
where tbl_out.column1 is null;

这很好用。但是有些列的 table1.product_id 值为 null。 所以对于这些记录 where table1.product_id = table2.product_id 条件不满足,记录没有更新。

我尝试按如下方式添加此条件 -

where (table1.product_id = table2.product_id OR table1.product_id is null)
and t1.id = tbl_out.id

但这将返回多于 1 行,以上更新语句将失败。 我知道在这种情况下可能很简单但无法弄清楚的问题。

有人可以帮我吗?

【问题讨论】:

  • 那么哪个查找表在子查询中提供colValuetable1table2?

标签: sql oracle sql-update


【解决方案1】:
   udate table1 tbl_out
 set column1 =
(select colValue from table1 t1, table2 t2
where nvl(table1.product_id,table2.product_id) = table2.product_id
and t1.id = tbl_out.id)
where tbl_out.column1 is null;

【讨论】:

  • 我试过了,但它给出了异常“子查询返回超过 1 行)
【解决方案2】:

我认为您正在寻找一个简单的相关子查询,这意味着您不需要子查询中的JOIN

update table1 tbl_out
    set column1 = (select t2.colValue
                   from table2 t2
                   where t2.product_id = tbl_out.product_id
                  )
    where tbl_out.column1 is null;

您可能还需要一个exists 子句:

update table1 tbl_out
    set column1 = (select t2.colValue
                   from table2 t2
                   where t2.product_id = tbl_out.product_id
                  )
    where tbl_out.column1 is null and
          exists (select 1
                  from table2 t2
                  where t2.product_id = tbl_out.product_id
                 );

编辑:

如果您在 table2 中有一个 NULL 值,并且您试图将其视为有效密钥:

update table1 tbl_out
    set column1 = (select t2.colValue
                   from table2 t2
                   where t2.product_id = tbl_out.product_id or
                         (t2.product_id is null and tbl_out.product_id is null)
                  )
    where tbl_out.column1 is null;

【讨论】:

  • 但这不会更新product_id为空的记录。我也想更新这些记录。
  • 有什么价值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 2013-06-28
  • 2011-04-26
  • 2021-01-29
  • 2012-10-28
相关资源
最近更新 更多