3
客户(cid、cname、caddress、ccity、cstate、czip、ccardnum)
产品(pid、pname、pbrand、pprice)
ShoppingCart(cartid, cid, active, totalprice)          
ShoppingCart.cid 对 Customer.cid 的引用
CartItem(cartid, pid, iprice, iquantity)     
CartItem.cartid 引用 ShoppingCart.cartid,
CartId.pid 引用 Product.pid
Order(oid, cartid, time, payprice) Order.cartid 对 ShoppingCart.cartid 的引用

创建触发器,当某个产品的价格发生变化时,更新包含该项目的任何活动购物车中该项目的价格,并更新这些购物车的总价格?

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;

上面的代码给了我错误,因为我正在更新用于更新购物车的购物车
当我尝试下面给出的代码工作正常但我无法更新购物车中的总价。有人可以帮我更新购物车 totalprice

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;

注意:我正在使用 MYSQL

样本数据:http ://www.sqlfiddle.com/#!2/8489e9/4/3

4

1 回答 1

1

尝试

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 ;

这是SQLFiddle演示

于 2013-11-11T04:56:30.913 回答