Auto-increment - automatic reset for each year(自动递增 - 每年自动重置)
问题描述
MySQL/InnoDB
MySQL/InnoDB
就我而言,我的收据应按年计算;1/2015、2/2015 ... 556/2015 等等.明年来的时候,柜台要重新从1开始,收据应该算为1/2016, 2/2016 ...
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 ...
如何定义每年自动重置的 auto_increment 字段?
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
注意:RCID 是标准的 PK 自动递增字段.
NOTE: RCID is standard PK auto incremented field.
推荐答案
在@RickJames 的帮助下,解决方案是:
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;
这篇关于自动递增 - 每年自动重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:自动递增 - 每年自动重置


- 更改自动增量起始编号? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01