2

I'm relatively new to triggers in MYSQL, so sorry if this is a pretty basic thing I'm trying to do. I've found how to set one up allowing a static update, however I haven't seen anything about how to use one of the fields from the inital update as a variable inside the trigger statement

Example:

Table 1, items:

id | name | total_stock
1 | item | 8
2 | item2 | 0

Table 2, item_options:

id | item_id | option | stock
1 | 1 | test | 5
2 | 1 | test2 | 3
3 | 2 | test | 0

If I then update item_options:

UPDATE `item_options` SET `stock`=7 WHERE `id`=1

Or insert a new item into item_options:

INSERT INTO `item_options` (`item_id`,`option`,`stock`) VALUES ('2','add','2')

Then I'd like (if it's possible) to use a trigger to update the total_stock in the items table with the SUM of stock in the item_options table with the same corresponding item_id.

So, I guess my question is in two parts:

  1. Is this possible?
  2. Can someone point me in the right direction of how to do this?

1 Answer 1

2

You can use the pseudo rows new or old as described here.

It should be something along these lines:

CREATE
TRIGGER my_trigger after insert, update
ON item_options FOR EACH ROW 
BEGIN
    update items set total_stock = (select sum(stock) from item_options where item_id = new.item_id) where item_id = new.item_id;
END;

Please note that I haven't tested it, but it should give you the general idea.

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

Comments

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.