Mysql触发器在2个表中进行计算?

时间:2014-04-14 21:38:34

标签: mysql sql if-statement triggers

如果order_status从0变为1或2,我试图制作一个必须进行减法的触发器。更新的order_status行中的数量值应该从另一个表中的quantity_in_stock中减去。这是我尝试过的,但它不适合我。

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 个答案:

答案 0 :(得分: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