Mysql – Get previous field’s value in MySQL trigger

MySQLtrigger

I am using a MySQL database and I have this kind of table.

IDRefHandler
x    299      
x    300      
x    301      

But I want to create a trigger (before insert) which will set automaticaly the Handler field. How to select the previous Handler value and just add one with a trigger ?

Is there any better way that storing the result of SELECT Handler FROM table order by Handler DESC LIMIT 1 and storing this in a VAR.
Is'nt it more efficient to use a magic word like OLD ? Or do I have to use a specific trick for this case?

PS : OLD is not usable in this case (source)

Best Answer

You are treating Handler like an AUTO_INCREMENT. Why not get rid of ID? Or use it instead of having an extra column?

Edit

Since you want to "reset to 0" the number at the start of the year... Assuming this is what you want, then converting it to a TRIGGER should work:

START TRANSACTION;  -- To keep other connections from overlapping
SELECT @year := ...,
       @next := MAX(Handler)+1
    FROM ...;
IF (YEAR(now() > @year) THEN
    SET @next := 0;
ENDIF
INSERT ... @next ...;
Related Question