I’ve an invoice number, this number is associated to a special document. This document has an id, formed by a progressive number and the current year, like this
222-2011
223-2011
224-2011
...
every year the progressive number restart from 1
1-2012
2-2012
3-2012
In the first place I thought to make a table with invoice_n, prog_n, year. prog_n is AUTO_INCREMENT and every year I’ll reset it. But you cant use an AUTO_INCREMENT field that isn’t a key. Anyway I’m going to reset the counter, and this is not so recommendable…
I can’t change the id format, I have to use that rule. Can I have an efficient design in some way?
the environment is a classic LAMP
many thanks!
Expanding on @Marius answer, I’d use a trigger to have MySQL set the invoicenumber automatically like so:
Note that you cannot access an auto-incrementing id in a
beforetrigger;Only in the
aftertrigger can you do this, but there you cannot change any values, so a little trickery is required.More trickery was used to make sure we use
invoice_dateas is in the select query so that an index on that field can be used.See:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_makedate