2014-04-14 67 views
0

我試圖做一個觸發器必須做一個減法,如果order_status從0更改爲1或2.更新的order_status行中的數量值應從另一個表中的quantity_in_stock中減去。這是我試過的,但它不適合我。Mysql觸發器在2個表中進行計算?

begin 
    DECLARE orderQuantity INT(11); 
    if old.order_status = 0 and new.order_status != 0 then 
    select quantity into orderQuantity from `order` where id=new.id; 
    update product_in_stock 
    set quantity_in_stock = sum(quantity_in_stock - orderQuantity) 
    where id=1; 
    end if; 
end 

回答

1

除非你自己定義sum功能,您使用的方法是錯誤的

,而不是set quantity_in_stock = sum(quantity_in_stock - orderQuantity)

應該set quantity_in_stock = sum(quantity_in_stock) - sum(orderQuantity)

但同樣,你不能使用直接像這樣的聚合函數,除非它在having子句中。

你能做什麼,declare two variable -> fetch the sum separately and store them to variable -> use them

DECLARE sum_quantity_in_stock INT(11); 
DECLARE sum_orderQuantity INT(11); 

select sum(quantity_in_stock) into sum_quantity_in_stock from sometable; 
select sum(orderQuantity) into sum_orderQuantity from sometable; 


set quantity_in_stock = sum_quantity_in_stock - sum_orderQuantity 
+0

謝謝拉胡爾,生病給一個鏡頭! –

+0

我需要添加表和東西到最後一行,對吧? –

+0

@MacLuc,添加我最後提到的代碼,然後在減法中使用變量。 – Rahul

相關問題