插入后的触发器不会为每一行触发

时间:2013-01-31 14:25:23

标签: mysql sql triggers

嘿,我有一个触发器,在更新后触发,定义如下:

CREATE DEFINER =  `root`@`localhost` TRIGGER `logs_m` AFTER UPDATE ON  
`logs_month` FOR EACH ROW
 BEGIN IF NEW.status =1 THEN INSERT INTO logs_payments( direction, 
TYPE , amount, agent_id, invoice_number ) 
VALUES ( 0, 3, NEW.reward_minutes, NEW.agent_id, NULL ) ,
 ( 0, 5, NEW.credit, NEW.agent_id, NULL ) ;

END IF ;
END

现在在logs_payments上我在插入后有一个触发器,其定义如下:

CREATE DEFINER =  `root`@`localhost` TRIGGER `payments_invoice` BEFORE INSERT ON 
 `logs_payments` 
FOR EACH
ROW BEGIN 
IF NEW.direction =0
THEN 
SET NEW.invoice_number = ( SELECT MAX( IFNULL( invoice_number, 100000000 ) ) +1
FROM logs_payments l
WHERE l.direction =0 ) ;

END IF ;

IF NEW.direction =1 THEN SET NEW.invoice_number = 
( SELECT MAX( IFNULL( invoice_number, 200000000 ) ) +1
FROM logs_payments l
WHERE l.direction =1 ) ;

END IF ;

END

现在,第一个插入的行invoice_number变为空,第二个变为正确的值。

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

解决了它,触发器在我的查询中遇到问题,因为我在第一次设置时没有价值:

SELECT MAX( IFNULL( invoice_number, 100000000 ) ) +1

应该是哪个错误

select ifnull(max(invoice_number),100000000)+1

现在它运作正常。