MySQL trigger learning summary bitsCN.com
# Create trigger, when adding record to order table is, update goods table delimiter $ create trigger trigger1 after insert on 'order' for each rowbeginupdate goods SET num = num-new.much WHERE id = new. gid; END $ execute insert into 'order' (gid, much) VALUES) then SELECT * FROM goods WHERE id = 1 find the number of TVs remaining 30 when executing insert into 'order' (gid, much) VALUES (2,100) the remaining number of refrigerators is found-77, which is a very obvious vulnerability. how can we fix it? Because the update event occurs after insert, we cannot filter the order quantity (much field in the order table) in advance. solution: When creating a trigger, change the "after" keyword to "before" and determine the number of orders. first, delete the trigger drop trigger trigger1; # CREATE trigger # trigger time: beforedelimiter $ create trigger trigger1BEFORE insert on 'order' for each rowbeginif new. much> 5 THENSET new. much = 5END IF; UPDATE goods SET num = num-new.much WHERE id = new. gid; END $
In this way, when you execute insert into 'order' (gid, much) VALUES (2,100), the number of orders written to the order table is actually only 5. Similarly, the inventory quantity in the goods table is only reduced by 5, because it is triggered before the insert operation.
Update operation to determine the order quantity
BitsCN.com