MySQL 字段值改变时触发

MySQL trigger when field change value

我在数据库中有 3 个 table:

  1. 产品

    CREATE TABLE `product` (
    `product_id` int(11) NOT NULL,
    `product_name` varchar(50) NOT NULL,
    `product_stock` int(11) NOT NULL,
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
  2. 交易

    CREATE TABLE `transaction` (
    `transaction_id` int(11) NOT NULL,
    `user_id` int(11) NOT NULL,
    `transaction_date` datetime NOT NULL,
    `transaction_status` ENUM('pending','process','cancel') NOT NULL DEFAULT 'pending'
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
  3. transaction_details

    CREATE TABLE `transaction_details` (
    `transaction_id` int(11) NOT NULL,
    `product_id` int(11) NOT NULL,
    `qty` int(11) NOT NULL,
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

如果交易 table 中的 transaction_status 更改为 "cancel" 如何根据 transaction_details 中的数量更新产品 table 中的 product_stock table 使用触发器

这个触发器应该做你想做的。在 transaction 上的 UPDATE 之后,它会更新交易中所有产品的库存(通过在所有三个表上使用 JOIN 来查找交易的相关产品):

CREATE TRIGGER update_stock 
AFTER UPDATE ON transaction
FOR EACH ROW
BEGIN
  IF NEW.transaction_status = 'cancel' THEN
    UPDATE transaction t
    JOIN transaction_details td ON td.transaction_id = NEW.transaction_id
    JOIN product p ON p.product_id = td.product_id
    SET p.product_stock = p.product_stock + td.qty;
  END IF;
END

Demo on dbfiddle