您可以使用三列来表示数字的不同部分,并使用视图或简单的 CONCAT 表达式来获取每张发票的整个数字。
然后要获得一个新数字,您将使用一个返回实际行 ID 或连接数字的函数插入一条记录。
我会做这样的事情:(为简洁起见,省略前导零)
DROP TABLE IF EXISTS invoces;
CREATE TABLE invoices (
id INT NOT NULL UNIQUE AUTO_INCREMENT
,company CHAR(2)
,number INT
,fiscal_year INT
, PRIMARY KEY (company, number, fiscal_year)
);
DROP PROCEDURE IF EXISTS spCreateInvoice;
DELIMITER $$
CREATE PROCEDURE spCreateInvoice
(
pCompany CHAR(2)
,pFiscalYear INT
)
BEGIN
INSERT INTO invoices (
company, fiscal_year, number
) SELECT
pCompany
, pFiscalYear
, 1+MAX(number)
FROM invoices
WHERE
fiscal_year=pFiscalYear;
SET @id = LAST_INSERT_ID();
SELECT CONCAT(i.company, i.number, i.fiscal_year) invoice_number, i.* from invoices i WHERE id = @id;
END;
$$
DELIMITER ;
CALL spCreateInvoice('MC', 12);
CALL spCreateInvoice('MC', 12);
CALL spCreateInvoice('MC', 12);
CALL spCreateInvoice('MC', 12);
CALL spCreateInvoice('MC', 13);
CALL spCreateInvoice('MC', 13);
CALL spCreateInvoice('MC', 13);
CALL spCreateInvoice('MC', 13);
您可以将其作为脚本针对您的 mysql 测试数据库运行,并查看以下输出:
invoice_number id company number fiscal_year
MC012 1 MC 0 12
invoice_number id company number fiscal_year
MC112 2 MC 1 12
invoice_number id company number fiscal_year
MC212 3 MC 2 12
invoice_number id company number fiscal_year
MC312 4 MC 3 12
invoice_number id company number fiscal_year
MC013 5 MC 0 13
invoice_number id company number fiscal_year
MC113 6 MC 1 13
invoice_number id company number fiscal_year
MC213 7 MC 2 13
invoice_number id company number fiscal_year
MC313 8 MC 3 13