2012-05-15 36 views
1

我有触发如下面的例子:如何使用MySQL触发器“假”,“开关”命令

BEFORE UPDATE ON icharts_user_stats FOR EACH ROW BEGIN 

IF (NEW.col1> OLD.col1 
    OR NEW.col2 > OLD.col2) THEN 
    SET NEW.col3 = NEW.col3+1; 
    SET NEW.col4 = NEW.col4+1; END IF; 

IF (NEW.col5> OLD.col5 
    OR NEW.col6 > OLD.col6) THEN 
    SET NEW.col7 = NEW.col7+1; END IF; 

IF (NEW.col8> OLD.col8 
    OR NEW.col9 > OLD.col9) THEN 
    SET NEW.col10 = NEW.col10+1; END IF; 

这有点像switch语句,只在一个“如果”将被执行的任何点。上面的代码工作,但如果第一个“如果”被击中,它仍然会经历所有其他IFS。

  1. 有没有更好的办法做到这一点?
  2. 以“走”之前“结束,如果”是个好主意

感谢

+0

或用[ELSEIF(http://dev.mysql.com/doc/refman/5.5/en/if-statement.html)类似:http://stackoverflow.com/questions/3056783/ – xQbert

回答

0

你试过吗?

BEFORE UPDATE ON icharts_user_stats FOR EACH ROW BEGIN 

    IF (NEW.col1> OLD.col1 
     OR NEW.col2 > OLD.col2) THEN 
     SET NEW.col3 = NEW.col3+1; 
     SET NEW.col4 = NEW.col4+1; 

    ELSEIF (NEW.col5> OLD.col5 
     OR NEW.col6 > OLD.col6) THEN 
     SET NEW.col7 = NEW.col7+1; 

    ELSEIF (NEW.col8> OLD.col8 
     OR NEW.col9 > OLD.col9) THEN 
     SET NEW.col10 = NEW.col10+1; END IF; 
+0

感谢的if-else条件-IN-A-mysql的触发怎么办,我退出-A系列 - 的 - 。我确实试过elseif,想知道是否有更好的方法。 – cldy1020

+0

比方说,我们必须条件1,上述条件2和Condition3。如果条件1为真,则它不关心或检查条件2和条件3。如果条件2为真,则不检查条件3。它确实符合您的要求。 –

0

试试这个。

BEFORE UPDATE ON icharts_user_stats FOR EACH ROW 
icharts_user_stats:BEGIN 

IF (NEW.col1> OLD.col1 
    OR NEW.col2 > OLD.col2) THEN 
    SET NEW.col3 = NEW.col3+1; 
    SET NEW.col4 = NEW.col4+1; 
    leave icharts_user_stats; 
END IF; 

IF (NEW.col5> OLD.col5 
    OR NEW.col6 > OLD.col6) THEN 
    SET NEW.col7 = NEW.col7+1; 
    leave icharts_user_stats; 
END IF; 

IF (NEW.col8> OLD.col8 
    OR NEW.col9 > OLD.col9) THEN 
    SET NEW.col10 = NEW.col10+1; 
    leave icharts_user_stats; 
END IF;