无法使用触发器更新正确的总价

时间:2017-02-03 16:40:33

标签: sql db2

我无法获得交易表的正确总价。 T001的总价假设为1000但是它与T002一起计算并变为2000。 任何人都可以看看我的触发器吗?谢谢你:D 我还想问一下如何为我的桌子设置基数,因为每笔交易最多只能有3个购买细节?

//My trigger
create trigger calc_totprice 
after insert or delete on purchase_detail 
for each row mode db2sql 

begin 

    if inserting then
    update transaction 
    set tot_price = (select sum(purchase_price) 
    from purchase_detail, transaction 
    where purchase_detail.trans_id = transaction.trans_id); 

    elseif deleting then 
    update transaction 
    set tot_price = (select sum(purchase_price) 
    from purchase_detail, transaction 
    where purchase_detail.trans_id = transaction.trans_id);
end if; 
end

//transaction table
TRANS_ID CON_ID CUS_ID TRANS_DATE TRANS_STATUS TOT_PRICE
-------- ------ ------ ---------- ------------ ---------
T001     CN01   CU001  2017-01-01 SUCCESS        2000.00
T002     CN01   CU001  2017-01-01 SUCCESS        2000.00

//purchase_detail table
PURCHASE_ID SEAT_ID TRANS_ID PURCHASE_PRICE
----------- ------- -------- --------------
P001        1       T001             500.00
P002        2       T001             500.00
P003        1       T001             500.00
P004        2       T002             500.00

1 个答案:

答案 0 :(得分:0)

我认为你想要相关的子查询:

if inserting then
    update transaction 
        set tot_price = (select sum(purchase_price) 
                         from purchase_detail
                         where purchase_detail.trans_id = transaction.trans_id
                        ); 

elseif deleting then 
    update transaction 
        set tot_price = (select sum(purchase_price) 
                         from purchase_detail
                         where purchase_detail.trans_id = transaction.trans_id
                       );