[英]How to write triggers for an update on two table one after another
Customer(cid, cname, caddress, ccity, cstate, czip, ccardnum) Product(pid, pname, pbrand, pprice) ShoppingCart(cartid, cid, active, totalprice) ShoppingCart.cid references to Customer.cid CartItem(cartid, pid, iprice, iquantity) CartItem.cartid references ShoppingCart.cartid, CartId.pid references Product.pid Order(oid, cartid, time, payprice) Order.cartid references to ShoppingCart.cartid
Create triggers that, when the price of a certain product changes, update the price of this item in any active shopping cart containing the item, and also updates the total price of these shopping carts?. 创建触发器,当某个产品的价格发生变化时,在包含该项目的任何活动购物车中更新此商品的价格,并更新这些购物车的总价?
CREATE TRIGGER priceupdate AFTER UPDATE ON product
FOR EACH ROW
BEGIN
UPDATE cartitem
SET iprice=new.pprice
WHERE pid=new.pid
and cartid in
(select cartid
from shoppingcart WHERE active='1');
UPDATE shoppingcart
SET totalprice =
(select sum(iprice*iquantity)
from cartitem WHERE cartid=new.cartid;
END;
Above code was givin me error because i am updating shopping cart which is used for updating cartitem 上面的代码是givin我错误,因为我正在更新用于更新cartitem的购物车
When I tried code given below worked fine but I am not able to update total price in shoppingcart.Can Someone help me with updating shopping cart totalprice 当我尝试下面给出的代码工作正常,但我无法更新shoppingcart的总价。可以有人帮我更新购物车总价
CREATE TRIGGER priceupdate AFTER UPDATE ON product
FOR EACH ROW
BEGIN
UPDATE cartitem
SET iprice=new.pprice
WHERE pid=new.pid and cartid in
(select cartid
from shoppingcart WHERE active='1');
END;
NOTE:I am using MYSQL 注意:我正在使用MYSQL
Sample data: http://www.sqlfiddle.com/#!2/8489e9/4/3 样本数据: http : //www.sqlfiddle.com/#!2/8489e9/4/3
Try 尝试
DELIMITER $$
CREATE TRIGGER product_priceupdate
AFTER UPDATE ON product
FOR EACH ROW
BEGIN
UPDATE cartitem i JOIN shoppingcart c
ON i.cartid = c.cartid
SET i.iprice = NEW.pprice
WHERE i.pid = NEW.pid
AND c.active = 1;
UPDATE shoppingcart c JOIN
(
SELECT cartid, SUM(iprice * iquantity) totalprice
FROM cartitem
WHERE cartid IN
(
SELECT DISTINCT i.cartid
FROM cartitem i JOIN shoppingcart c
ON i.cartid = c.cartid
WHERE i.pid = NEW.pid
AND c.active = 1
)
GROUP BY cartid
) q
ON c.cartid = q.cartid
SET c.totalprice = q.totalprice;
END$$
DELIMITER ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.