Search code examples
phpmysqlauto-increment

MySQL AUTO_INCREMENT according to year


Im creating a ticketing system and this is my table structure:

CREATE TABLE tix_sip
(
tktNum INT UNSIGNED NOT NULL,
sipNum INT UNSIGNED AUTO_INCREMENT,
PRIMARY KEY( sipNum ),
FOREIGN KEY(tktNum) REFERENCES Tix (tktNum)
);

what I would like to happen with my sipNum is to be numbered according to year.

Example: 20140001, 20140002, ..20140334, 20140335....

How do I make it change the first 4 digits automatically so everytime next year comes, it will create new\another set of AUTO_INCREMENTed numbers

Example: 20150001, 20150002........ 20160001, 20160002..

btw, Im using php code for my program, in case that could help if a solution would be creating a function. Thanks


Solution

  • You can use MySQL Custom AUTO_INCREMENT values as follows: (read the article first)

    Create table and trigger:

    CREATE TABLE test
    (
        id int not null auto_increment primary key,
        year_autonum varchar(20)
    );
    
    delimiter //
    DROP TRIGGER IF EXISTS custom_autonums_bi//
    
    CREATE TRIGGER custom_autonums_bi BEFORE INSERT ON test
    FOR each ROW
    BEGIN
       SET NEW.year_autonum = getNextCustomSeq(year(now()),year(now()));
    END//
    
    delimiter ;
    

    Insert some values:

    insert into test(id) values (null);
    insert into test(id) values (null);
    insert into test(id) values (null);
    ...
    

    Select data:

    mysql> select * from test;
    +----+--------------+
    | id | year_autonum |
    +----+--------------+
    |  1 | 2014-000001  |
    |  2 | 2014-000002  |
    |  3 | 2014-000003  |
    |  4 | 2014-000004  |
    |  5 | 2014-000005  |
    |  6 | 2014-000006  |
    +----+--------------+
    6 rows in set (0.00 sec)
    

    You can change the procedure getNextCustomSeq to ommit the slash - sign.