使用t2中的字段在t1上插入之前触发

时间:2017-08-19 10:26:31

标签: mysql triggers inner-join

我有 goods_input goods_input_price 表格,并希望在 goods_input 中插入新行时计算总金额。 触发器如下:

DELIMITER $$

USE `gym`$$

DROP TRIGGER /*!50032 IF EXISTS */ `total`$$

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `total` BEFORE INSERT ON `goods_input` 
    FOR EACH ROW BEGIN

       SET new.goods_input_total_amount=new.goods_input_quantity*goods_input_price.`price_goods_input_price` 
       WHERE goods_input.`id_goods_input_price`=goods_input_price.`id_goods_input_price`;

    END;
$$

DELIMITER ;

这是错误消息:

  

错误代码:1064您的SQL语法出错;检查   手册,对应右边的MySQL服务器版本   在' where附近使用的语法   goods_input id_goods_input_price = goods_input_price.`id_goods_input_price&#39。在第6行

1 个答案:

答案 0 :(得分:0)

set语句没有where子句。如果您想要来自另一个表的数据,那么您需要通过select将它们提取到触发器中的变量中。

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `total` BEFORE INSERT ON `goods_input` 
    FOR EACH ROW BEGIN
        DECLARE input_price integer; /*use whatever datatype you have in your db for the price */
        SELECT price_goods_input_price INTO input_price FROM goods_input_price
        WHERE id_goods_input_price=NEW.id_goods_input_price LIMIT 1;
        SET new.goods_input_total_amount=new.goods_input_quantity*input_price;

    END$$