创建触发器来求和表并插入到另一个表中

gg0vcinb  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(319)

我有一个sql函数,它是

SELECT p.id, coalesce(ig.NumReceived,0) as NumReceived,
        coalesce(og.NumShipped,0) as NumShipped, p.Label,
        coalesce((p.StartingInventory-og.NumShipped+ig.NumReceived), p.StartingInventory)
        as OnHand, p.ProductName,
        p.StartingInventory, p.MinimumRequired
        from products p
        left outer join (
            select productid, sum(NumReceived) as NumReceived
            from incoming
            group by productid
        ) as ig on p.id = ig.productid
        left outer join (
            select productid, sum(NumberShipped) as NumShipped
            from outgoing
            group by productid
        ) as og on p.id = og.productid');

我这样做是为了不必在products中为“incoming”创建一个列,我可以直接显示结果,但是现在我想在products中为incoming和outgoing创建一个列。如果我能解决传入的问题,我可能也能解决传出的问题。
产品表如下所示

id(int primary key), MinimumRequired(int), StartingInventory(int), Label(text), ProductName(text), inc(int)

inc列现在是空的,因为我刚刚添加了它。看起来像这样。

id(int primarykey), SupplierId(int), ProductId(int), NumReceived(int),  PurchaseDate(date)

为了让您了解gui,它是

这就是我目前所拥有的

CREATE TRIGGER inc_update
  AFTER UPDATE ON incoming
  FOR EACH ROW 
BEGIN
  UPDATE products
    SET inc = sum(NEW.NumReceived)
    WHERE products.id = NEW.ProductId;
END;
z9gpfhce

z9gpfhce1#

大概你想要:

DELIMITER $$

CREATE TRIGGER inc_update
  AFTER UPDATE ON incoming
  FOR EACH ROW 
BEGIN
  UPDATE products
    SET inc = COALESCE(inc, 0) + NEW.NumReceived
    WHERE products.id = NEW.ProductId;
END;$$

DELIMITER ;

也就是说,您不需要聚合,因为您一次只添加一个值。
对于形式正确性,您应该在 update 以及 delete 也。

相关问题