MySQL trigger learning summary _ MySQL

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.