The difference between MySQL trigger before and after

Source: Internet
Author: User

Let's start with a test: the Product table G and the Order form O and the trigger hypothesis: the product table has a product 1, the quantity is 10; we insert a record into the order form: INSERT into O (Gid,much) VALUES (1,20), and you will find that the number of items 1 becomes 10. This is where the problem is, because the trigger we created earlier is after, which means that the triggered statement is executed after the order is inserted, so that we cannot determine the purchase quantity of the new insert order. First of all, the difference between after and before: After is the first to complete the data additions and deletions, and then trigger, trigger the statement later than the monitoring and deletion of the operation, can not affect the previous additions and deletions to change the action, that is, first insert the order record, and then update the quantity of the goods; before is the first trigger, then add The triggering statements are preceded by additions and deletions to the monitor, and we have the opportunity to judge and modify the actions that will occur; we use a typical case to differentiate between them, create a new trigger: #监视地点: Commodity table o# Monitoring event: insert# Trigger Time: before# Trigger Event: Update case: When an order record is added, the number of items in the order is determined, if the quantity is greater than 10, the default is 10create trigger Tg6before insert on ofor each rowbegin if New.much ;  Ten then Set New.much = 10;  End If; Update g Set num = Num-new.much WHERE id = new.gid;end$ executed, delete the after trigger created earlier, then insert an order record: INSERT into O (gid,much) valus ( 0) $ execution will find the number of order records changed to 10, the number of goods 1 becomes 0, there will be no negative.

The difference between the before and after of MySQL triggers

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.