The difference between MySQL trigger before and after

Source: Internet
Author: User

Let's do a test first:

The Product table G and the Order form O and the trigger are then built

Hypothesis: If the commodity table has a commodity of 1, the quantity is 10;

We insert a record into the order form:

INSERT into O (Gid,much) values (1,20);

Will find that the number of items 1 has changed to 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.

Let's talk about 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 order records, and then update the number of goods;

Before is the first to complete the trigger, then increase the deletion, trigger the statement before the monitoring of the additions and deletions, we have the opportunity to judge, modify the impending operation;

We use a typical case to differentiate between them and create a new trigger:

#监视地点: Product Table O

#监视事件: Insert

#触发时间: Before

#触发事件: Update

Case: When a new order record is added, the number of items in the order is judged, if the quantity is greater than 10, the default is changed to 10

Create Trigger Tg6

Before insert on O

For each row

Begin

If New.much > ten Then

Set New.much = 10;

End If;

Update g Set num = Num-new.much where id = new.gid;

end$

After execution, delete the previously created after trigger and insert an order record:

INSERT into O (gid,much) valus (1,20) $

After execution, you will find that the number of order records becomes 10, and the number of items 1 becomes 0, so there will be no negative numbers.

The difference between MySQL trigger before and after

Related Article

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.