1

I have 3 table in database:

  1. product

    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. transaction

    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;
    

if transaction_status in transaction table changed to "cancel" how to update product_stock in product table based on qty in transaction_details table using trigger

1 Answer 1

2

This trigger should do what you want. After an UPDATE on transaction it updates the stock of all products in the transaction (by using JOINs on all three tables to find the relevant products for the transaction):

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the answer, but I'm facing mysql error #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.