2012-05-15 34 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;