【问题标题】:Multiple if statements in MySQL triggerMySQL触发器中的多个if语句
【发布时间】:2013-01-28 15:41:28
【问题描述】:

如果 MySQL 触发器中有多个 if 语句,最好的方法是什么?

目前我的 SQL 如下所示:

IF NOT (NEW.status <=> OLD.status) THEN
  {my sql}

ELSEIF NOT (NEW.actual <=> OLD.actual) THEN
  {my sql}
END IF

乍一看,这似乎有效。但是,我注意到当多个 (else)if 语句为真时,只有第一个被执行(就像在 PHP 中一样)。

我怎样才能只使用多个 if,不一定是 elseif,以便执行超过 1 条语句?不可能使用相同的操作创建多个触发器,至少 phpMyAdmin 是这样显示的。在一个触发器中放置多个 if 会导致错误。

【问题讨论】:

    标签: mysql sql triggers phpmyadmin


    【解决方案1】:

    这样使用:

     IF (NEW.status <> OLD.status) THEN
        <statement>
     ELSEIF (NEW.actual <> OLD.actual) THEN
         <statement>
     END IF;
    

    【讨论】:

    • 产生同样的效果?当第一个 IF 为真时,不执行 elseif。
    【解决方案2】:

    想通了。我没有使用 phpMyAdmin 中的可视 GUI 来创建触发器,而是使用纯 SQL。

    所以我使用了这个 SQL:

    delimiter //
    create t1
    after update
    on my_table
    for each row
        begin
            IF (NEW.status <> OLD.status) THEN
                {your sql}
            END IF;
    
            IF (NEW.actual <> OLD.actual) THEN
                {your sql}
            END IF;     
        end;//
    delimiter ;
    

    效果很好。在 phpMyAdmin GUI 中查找触发器时,我注意到这是因为必须添加 beginend;

    【讨论】:

    • 我注意到这是因为开始和结束;必须添加.....这才是真正的重点
    【解决方案3】:
    if(NEW.shift = 0 )then
    
    SELECT `max_morning` , `count_morning` into @max_morning , @count_morning FROM `count_reserve` where `date` = NEW.date_reserve;
    if(@count_morning is NULL and @max_morning is NULL) then
    
      select `max_morning` , `max_evening` into @max_morning , @max_evening   from `work_time` where `day` = new.day;
    
        insert into `count_reserve` (`date`, `count_morning` ,      `count_evening`,`from_morning`, `to_morning`, `max_morning`, `from_evening`, `to_evening`, `max_evening` , `status_morning` , `status_evening`) values (NEW.date_reserve , 1 , 0 , NULL, NULL, @max_morning , NULL, NULL, @max_evening ,1, 1);
    
    
    end if
    end if
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 2019-02-02
      • 2012-04-13
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多