Let’s say I have two tables as shown:
user
id plan course_limit username
10 0 ahmad
note: plan is enum field containing '','a','b','c'.
course
id user_id username
1 10 ahmad
Now I want when a user insert into course as shown I want the course_limit to increment by 1 for that user so that I can apply a limit.
You can create a trigger with the following code.
Some explanation
You create a trigger that fires once for every row
FOR EACH ROWthat is insertedAFTER INSERTinto table course.When you insert into the table you can trigger
BEFOREandAFTERthe insert is done.If you want to be able to prevent the insert you fire before, if you just want to do useful work, you fire after.
The inserted fields can be accessed via a dummy table ‘new’.
So here after each insert the UPDATE statement gets executed.
More trigger options
You can also use triggers
BEFORE UPDATE,AFTER UPDATE,BEFORE DELETEandAFTER DELETE.In the update and delete cases you get an extra dummy table
oldthat you can use to refer to the data in the table before the update or delete happened.Lots more is possible, but I’ll keep it simple for now.
See http://forge.mysql.com/wiki/Triggers for more info.