提问者:小点点

Mysql触发器未更新记录


我有两张表“产品”和“库存”。表将包含所有产品。在库存表中,我每次都将产品的库存保存为一个新的条目。

我有两种类型的产品。“1”类型的产品将以stock作为编号,“0”类型的产品将以stock作为重量。因此,在products表中,我创建了两列“stock_weight(保持在库存表中输入的总重量)”和“pieces(保持在库存表中输入的总数量)”。

为此,我在stock表上创建了一个触发器,每当我将新记录插入到这个表中时,它将执行以更新products表中的总重量或数量(件)。下面是触发器的代码:

BEGIN
DECLARE product_type tinyint default 0;

SET product_type = (Select product_type from products where id = NEW.product_id);

IF (product_type = 0) THEN
    UPDATE products set stock_weight = stock_weight + NEW.net_weight where id = NEW.product_id;
ELSE
    UPDATE products set stock_pieces = stock_pieces + NEW.pieces where id = NEW.product_id;
END IF;
END  

但在为任何产品在stock表中插入新记录后,product表中不会更新任何内容。我已经调试了触发器,触发器正在执行,但在product表中没有更新。

谁能告诉我,我错过了什么,我做错了什么?


共1个答案

匿名用户

不要为变量赋予与列相同的名称并预期为NULL

DROP TABLE IF EXISTS PRODUCTS,STOCKS;
create table products(id int,product_type int,stock_weight int,stock_pieces int);
create table stocks(product_id int,net_weight int,pieces int);
drop trigger if exists t;
delimiter $$
create trigger t after insert on stocks
for each row
BEGIN
DECLARE vproduct_type tinyint default 0;

SET vproduct_type = (Select product_type from products where id = NEW.product_id);

IF (vproduct_type = 0) THEN
    UPDATE products set stock_weight = coalesce(stock_weight,0) + NEW.net_weight where id = NEW.product_id;
ELSE
    UPDATE products set stock_pieces = coalesce(stock_pieces,0) + NEW.pieces where id = NEW.product_id;
END IF;
END  $$
delimiter ;

insert into products values(1,1,null,null),(2,0,null,null);

insert into stocks values(1,null,10),(2,10,null);

select * from products;

+------+--------------+--------------+--------------+
| id   | product_type | stock_weight | stock_pieces |
+------+--------------+--------------+--------------+
|    1 |            1 |         NULL |           10 |
|    2 |            0 |           10 |         NULL |
+------+--------------+--------------+--------------+
2 rows in set (0.001 sec)