创建SUM表的触发器并插入另一个

时间:2018-08-15 18:28:53

标签: php mysql sql mysqli triggers

我有一个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表看起来像这样

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有所了解,就是这样 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;

1 个答案:

答案 0 :(得分:1)

大概是您想要的:

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 ;

也就是说,您不需要汇总,因为您可以一次添加一个值。

为了形式上的正确性,您还应该在updatedelete上使用触发器。