简体   繁体   English

根据另一列的计算创建MYSQL触发器以更新列

[英]Create MYSQL Trigger To Update Column based on calculation of another column

I have this table 我有这张桌子

id     price     qty     points

How can I create a trigger so that whenever I update the column price, the column points will be updated based on the calculation of price DIV 10 DIV qty? 如何创建触发器,以便每当更新列价格时,都会基于价格DIV 10 DIV数量的计算来更新列点?

I have tried but it does not work and it doesn't update the column points. 我已经尝试过,但是它不起作用,并且不会更新列点。

delimiter $$
drop trigger if exists cart_update_rewards$$
create trigger cart_update_rewards
after update on cart
for each row 
begin
SELECT `price` DIV 10 DIV `quantity` as points FROM `cart`;
end$$ 

If you want to assign the value to a column in cart , use a "before update" trigger and assign the value in new : 如果要将值分配给cart的列,请使用“更新前”触发器,并在new分配值:

delimiter $$
drop trigger if exists cart_update_rewards$$
create trigger cart_update_rewards
before update on cart
for each row 
begin
    set new.points = new.price DIV 10 DIV new.quantity ;
end$$ 

I have resolved it with help from @GordonLinoff. 我已经在@GordonLinoff的帮助下解决了它。

DELIMITER //
CREATE TRIGGER trigger_name
BEFORE UPDATE
ON cart FOR EACH ROW
BEGIN
-- trigger code
set new.`reward_points` = new.cart_price DIV 1;
END; // 
DELIMITER ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM