问题
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.
回答1:
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
回答2:
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;
来源:https://stackoverflow.com/questions/30167587/auto-increment-automatic-reset-for-each-year