当字段改变值时MySQL触发

时间:2019-01-30 05:05:34

标签: mysql database triggers database-trigger

我在数据库中有3个表:

  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;
    

如果事务表中的transaction_status更改为“取消”,则如何使用触发器根据transaction_details表中的数量更新产品表中的product_stock

1 个答案:

答案 0 :(得分:1)

此触发器应执行您想要的操作。在UPDATE上的transaction之后,它会更新交易中所有产品的库存(通过在所有三个表上使用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