MySQL Trigger: Before Insert or After Insert

2019-09-14 22:25发布

问题:

I am working on some database project (PHP/MySQL) used for billing.

Whenever a new bill is created I want to generate a bill number consisting of year, week and increment number. I would like to do this with a trigger. The trigger will use the existing billnumbers to find the increment number or start with a fresh increment for the first bill n a new week and/or new year.

Apart from generating the bill number, I can do a BEFORE INSERT trigger and set the NEW.billnumber to the newly generated billnumber. It is also possible to do an AFTER INSERT and update the record with the generated billnumber.

My question is which one should I choose. BEFORE INSERT or AFTER INSERT? I did search for this, but I can't find a good argumentation when to use BEFORE or AFTER.

回答1:

Found out that it can be done with BEFORE INSERT only because MySQL does not allow manipulation of the table that triggered the AFTER INSERT trigger.