mysql触发器在后续查询中没有标识new.entity?

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

我在“purchase\u invoice”表上设置了一个触发器,它应该为“purchase\u stock”表中的发票项添加相应的库存交易,并更新“stock”表中的库存单位:

CREATE TRIGGER addStock AFTER INSERT ON purchase_invoice
FOR EACH ROW

    INSERT INTO 
    purchase_stock
    (
       purchase_invoice_id,
       item_id,
       units,
       ...
    )
    VALUES
    (
       NEW.id,
       NEW.item_id,
       NEW.units
       ...
    );

    UPDATE 
       stock 
    SET 
       units = units + NEW.units 
    WHERE 
       item_id = NEW.item_id;
...

但我有以下错误:

Unknown column 'NEW.units'   in field list
Unknown column 'NEW.item_id' in 'where clause'
camsedfj

camsedfj1#

根本没有 BEGIN 之后 FOR EACH ROW 因此mysql解释为触发器仅用一条insert语句定义,并单独考虑update语句。这就是为什么您会收到错误消息。显然,您缺少相应的 END 也。
正确的代码如下所示:

DELIMITER \\
CREATE TRIGGER addStock AFTER INSERT ON purchase_invoice
FOR EACH ROW
BEGIN
    INSERT INTO 
    purchase_stock
    (
       purchase_invoice_id,
       item_id,
       units,
       ...
    )
    VALUES
    (
       NEW.id,
       NEW.item_id,
       NEW.units
       ...
    );
    UPDATE 
       stock 
    SET 
       units = units + NEW.units 
    WHERE 
       item_id = NEW.item_id;
    ...
END\\

DELIMITER ;

相关问题