使用 where exists 而不是 join 在 DB2 中更新

Update in DB2 using where exists instead of join

我正在尝试在 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 for i 不允许更新 table 来自 DB2LUW 允许

你有两个解决方案

一个是 UPDATE 使用一个子查询 select 要更新的行,另一个是获取 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 以避免意外