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