MySQL触发器-插入另一个表时更新表

时间:2019-07-29 07:19:15

标签: mysql triggers

我有三个表:

导入表:

import_id  | import_date
-------------------------
   1       | 2019/07/29
   2       | 2019/07/28

ImportItem表:

import_id    |  product_id |  quantity
-------------------------------------
    1        |     1       |   50
    1        |     2       |   60
    1        |     3       |   20

产品表:

product_id   |  quantity   
---------------------------
    1        |     10       
    2        |     5       
    3        |     15      

我要在插入ImportItem表时在产品表中创建触发器更新数量。
我尝试了以下查询:

CREATE TRIGGER trigger_name
AFTER INSERT
ON import_item FOR EACH ROW
BEGIN
declare _import_id int;
declare _product_id int;
declare _quantity int;
SELECT quantity,product_id
INTO _quantity,_product_id
FROM import_item
WHERE import_id=NEW.import_id;
update product set quantity = _quantity where product_id=_product_id;
END

任何帮助,不胜感激!非常感谢!

1 个答案:

答案 0 :(得分:0)

CREATE TRIGGER trigger_name
AFTER INSERT
ON import_item FOR EACH ROW
BEGIN
    UPDATE product SET quantity = NEW.quantity WHERE product_id= NEW.product_id;
END