Mysql使用if语句和变量触发

时间:2014-10-31 16:36:08

标签: mysql triggers

好的,所以我需要创建一个需要使用if elseif和另一个elseif的后插入触发器。 if,elseif,elseif需要基于从其他3个数据库表中获取的查询数据。我想知道是否有一种方法可以做到这一点,而无需在开始时运行所有三个查询。

BEGIN
    SET @t3  = (SELECT team_id FROM team_trans WHERE key1 = NEW.trans_id LIMIT 1);
      SET @t2 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.STORE_ID AND team_assignments.type = 1);
      SET @t1 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.CUSTOMER_ID AND team_assignments.type = 0);
IF (@t3) THEN
               INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (@t3, NEW.id, 0, 1 );      
      ELSEIF (@t1) THEN
          INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (@t1, NEW.id, 0, 1 );
      ELSEIF (@t2) THEN
          INSERT INTO team_trans (team_id, trans_id, type, misc_id) VALUES (@t2, NEW.id, 0, 1 );
      END IF;
    END

1 个答案:

答案 0 :(得分:1)

选项是:

...
BEGIN    
    /*
    SET @t3  = (SELECT team_id FROM team_trans WHERE key1 = NEW.trans_id LIMIT 1)//
    SET @t2 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.STORE_ID AND team_assignments.type = 1)//
    SET @t1 = (SELECT team_id FROM team_assignments WHERE team_assignments.misc_id = NEW.CUSTOMER_ID AND team_assignments.type = 0)//
    */    
    IF (SELECT @t3 := team_id
            FROM team_trans
            WHERE key1 = NEW.trans_id 
            LIMIT 1) THEN
        INSERT INTO team_trans (team_id, trans_id, type, misc_id)
        VALUES
        (@t3, NEW.id, 0, 1);      
    ELSEIF (SELECT @t1 := team_id
                    FROM team_assignments
                    WHERE team_assignments.misc_id = NEW.CUSTOMER_ID AND team_assignments.type = 0) THEN
        INSERT INTO team_trans (team_id, trans_id, type, misc_id)
        VALUES
        (@t1, NEW.id, 0, 1);
    ELSEIF (SELECT @t2 := team_id
                    FROM team_assignments
                    WHERE team_assignments.misc_id = NEW.STORE_ID AND team_assignments.type = 1) THEN
        INSERT INTO team_trans (team_id, trans_id, type, misc_id)
        VALUES
        (@t2, NEW.id, 0, 1);
    END IF;
END//
...