当一个单元格的值为0时,我如何删除带有触发器的行?

问题描述 投票:0回答:1

我有一个购物车表,客户可以从购物车中添加、更新或删除一个产品。另一种删除商品的方法是在数量列中放入0值。我尝试使用触发器来删除该行,但它没有删除它。我该如何解决这个问题?

这是我试过的,但没有效果

DELIMITER $$
CREATE TRIGGER tr_remove_cart_item
AFTER UPDATE ON cart
for each row
IF NEW.quantity <= 0
THEN
    DELETE FROM cart
    WHERE NEW.quantity <= 0;
END IF;

DELIMITER ;
mysql database triggers sql-delete
1个回答
0
投票

触发器不能对它所发射的表进行操作。所以你所要求的基本上不能用触发器来完成。

另一种方法是使用存储过程来实现这些逻辑。

下面是一个例子,假设表 cart 有列 cart_id, item_idquantity:

delimiter //
create procedure update_cart(
    in p_cart_id int,
    in p_item_id int,
    in p_quantity int
)
begin
    if p_quantity > 0 then
        update cart 
        set quantity = p_quantity 
        where cart_id = p_cart_id and item_id = p_item_id;
    else
        delete from cart
        where cart_id = p_cart_id and item_id = p_item_id;  
    end if;
end //
delimiter ;

该程序接收三个参数作为输入;如果是: quantity 大于 0,它 updatecart 桌子,否则 delete的相应记录。

你可以用下面的代码运行这个过程。

call update_cart(1, 2, 3);

其中 1, 2, 3 分别是 cart_id, item_idquantity.

© www.soinside.com 2019 - 2024. All rights reserved.