Auto-increment - automatic reset for each year

2019-02-24 15:26发布

MySQL/InnoDB

In my case my receipts should be counted on yearly basis; 1/2015, 2/2015 ... 556/2015 and so on. When next year comes, the counter should start from 1 again and receipts should be counted as 1/2016, 2/2016 ...

How to define auto_increment field which will reset itself on yearly basis?

RCID | RCNO | RCYEAR | ...
=====+======+========+====
 200 |    1 |   2015 |
 201 |    2 |   2015 |
 ... |  ... |   2015 |     
 756 |  556 |   2015 |     <- last receipt in 2015
 757 |    1 |   2016 |     <- yearly counter restarted

NOTE: RCID is standard PK auto incremented field.

2条回答
等我变得足够好
2楼-- · 2019-02-24 15:59

After help from @RickJames the solution is:

CREATE TRIGGER ReceiptNumber BEFORE INSERT ON receipts FOR EACH ROW
BEGIN
  SET NEW.rcyear=YEAR(NOW());
  SET NEW.rcno=(SELECT IFNULL(MAX(rcno),0)+1 FROM receipts WHERE rcyear=YEAR(NOW()));
END;
查看更多
神经病院院长
3楼-- · 2019-02-24 16:23

This is not a proper usage of AUTO_INCREMENT. If you want something special like you describe, do it yourself.

MyISAM has a feature like that (the second column in a PRIMARY KEY could be AUTO_INCREMENT like that). But InnoDB is preferred these days. A way to simulate it is in my blog

查看更多
登录 后发表回答