【问题标题】:Update in DB2 using where exists instead of join使用 where exists 而不是 join 在 DB2 中更新
【发布时间】:2021-10-30 22:57:05
【问题描述】:

我正在尝试在 DB2 中执行更新,我开始尝试使用内部连接,但 DB2 不允许这样做。我将其更改为使用 'where exists' 子句,但现在它告诉我在我的set 子句中找不到main_discount(我假设是因为直到后来的where exists 才引用它

如果我还没有我需要的列值,如何使这项工作按预期工作?

update main_library.details
set less_amount = ROUND(cast (price as float) * (main_discount/100),2)
    where exists(
        select 
               price,
               wholesale_num,
               main_discount,
               startDate,
               endDate
        from main_library.details D
            inner join 2nd_library.discounts DISC
                on D.wholesale_num = DISC.wholesale_num
            where wholesale_num  = 123
    )
limit 200;

【问题讨论】:

  • 请用更精确的标签标记您的问题:db2-400、db2-luw 或 db2-zos。答案不一样。
  • @nfgl 啊,对不起。是db2-400,我刚刚更新了标签

标签: sql db2 db2-400


【解决方案1】:

DB2 for i 不允许 DB2LUW 允许的 UPDATE 表 FROM

你有两个解决方案

一个是UPDATE 使用一个子查询来选择要更新的行,另一个是获取 main_discount 的值

update main_library.details as main
set less_amount = ROUND(cast (price as float) * (
   (select main_discount from 2nd_library.discounts DISC
            where wholesale_num  = main.wholesale_num)
  /100),2)
    where exists(
        select 0 from 2nd_library.discounts DISC
            where wholesale_num  = main.wholesale_num
    )

另一个是MERGE

MERGE INTO main_library.details main
using(
select wholesale_num, main_discount from 2nd_library.discounts DISC
) disc on disc.wholesale_num = main.wholesale_num
when matched then
  update set less_amount = ROUND(cast (price as float) * (main_discount)/100),2)

也许你应该使用 DECFLOAT 而不是 FLOAT 以避免意外

【讨论】:

  • 好的 第一个选项似乎让我得到了我需要的东西,我很感激。为了安全起见,我现在也在使用 DECFLOAT,再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 2015-06-05
相关资源
最近更新 更多