MySQL 更新/插入触发器自动递增分组
我有一个表单,用户可以在其中单击一个标志(如果是,则为 1,如果不是,则为 0)来创建收据编号(receiptno)。我希望这通过数据库实现自动化——因此我想到了触发器。
我想在一个组上创建一个自动增量。
架构:
CREATE TABLE booking
(BuchungId int, `category` int, `year` int, `flag` int, receiptno int)
;
INSERT INTO booking
(BuchungId,`category`, `year`, `flag`, receiptno)
VALUES
(1, 1, 2016, 1, NULL),
(2, 1, 2017, 1, NULL),
(3, 1, 2017, 0, NULL),
(4, 2, 2017, 1, NULL),
(5, 2, 2017, 1, NULL),
(6, 1, 2017, 1, NULL),
(7, 1, 2017, 0, NULL),
(8, 1, 2017, 1, NULL)
;
我创建了触发器的主体:
CREATE TRIGGER trigger1
BEFORE UPDATE
ON booking
FOR EACH ROW
BEGIN
IF (new.Flag = 1) THEN
SET New.receiptno = COALESCE(old.receiptno,0)+1;
end IF;
end
现在我想按类别和年份更新(或插入)一组收据。
因此最终产生如下表:
(1, 1, 2016, 1, 1),
(2, 1, 2017, 1, 1),
(3, 1, 2017, 0, NULL),
(4, 2, 2017, 1, 1),
(5, 2, 2017, 1, 2),
(6, 1, 2017, 1, 2),
(7, 1, 2017, 0, NULL),
(8, 1, 2017, 1, 3)