[英]Mysql trigger is not updating record
I have two tables "Products" and "stocks".我有两个表“产品”和“股票”。 Products table will have all the products.
产品表将包含所有产品。 In stock table, I save stock of product as a new entry each time.
在库存表中,我每次都将产品的库存保存为新条目。
I have two type of products.我有两种产品。 Product of "1" type will have stock as a number and product of "0" type will have stock as weight.
“1”类型的产品将有库存作为数字,“0”类型的产品将有库存作为重量。 Therefore, in products table I have created two columns "stock_weight (to keep total weight entered in stock table)" and "pieces (to keep total quantity entered in stock table)".
因此,在产品表中,我创建了两列“stock_weight(保持在库存表中输入的总重量)”和“件(保持在库存表中输入的总数量)”。
For this I have created a trigger on stock table that will execute to update total weight or quantity(pieces) in products table whenever I will insert new record into this table.为此,我在库存表上创建了一个触发器,每当我将新记录插入此表时,它将执行以更新产品表中的总重量或数量(件)。 Below is the code of trigger:
下面是触发器的代码:
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
But after inserting new record in stock table for any product, nothing is updating in product table.但是在任何产品的库存表中插入新记录后,产品表中没有任何更新。 I have debugged trigger and trigger is executing but nothing is updating in product table.
我已经调试了触发器并且触发器正在执行,但产品表中没有任何更新。
Can someone please tell me what I am missing and what thing I am doing wrong?有人可以告诉我我错过了什么以及我做错了什么吗?
Don't give variables the same name as columns and anticipate nulls不要为变量赋予与列相同的名称并预期为空
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.