如何在插入触发器后处理mysql中的冗余

时间:2016-10-25 06:22:40

标签: mysql

我有一个插入后触发器,当执行触发器时,它会在另一个表中插入多行。我只希望插入单个条目。

以下是查询:

CREATE TRIGGER Afterinsert_userbadge AFTER INSERT ON `user_match_result`FOR EACH ROW  
BEGIN  
DECLARE goalCount INT(10);  
DECLARE badgeId BIGINT(20);  
declare userId bigint(20) default 0 ;  

SELECT sum(goal) INTO goalCount FROM user_match_result WHERE user_id = NEW.user_id;  

IF  goalCount > = 1 THEN  

    SELECT badge_id INTO badgeId FROM badge_master WHERE name  = 'FIRST OF MANY';  
    SELECT user_id into userId FROM user_badges 
    WHERE badges_id = badgeId and user_id = NEW.user_id 
    AND match_id = NEW.match_id;  

    IF (userId <> 0) THEN
        INSERT INTO user_badges(badges_id,user_id,match_id,created_date)   
        SELECT badgeId, NEW.user_id,NEW.match_id,NEW.created_date 
        FROM user_match_result;   
    END IF;  

END IF;  

END  

如果在user_match_result表上完成了单个条目,则在user_badges表中插入34行。

0 个答案:

没有答案