web-dev-qa-db-ja.com

IF THENを使用したMysqlトリガー

私のストレージはINNODBです。IFステートメントで2つのクエリを使用してトリガーを作成しようとしています。ダウンすると、エラーが発生するトリガーを確認できます

delimiter |
CREATE TRIGGER count_delete_videos BEFORE DELETE ON videos
  FOR EACH ROW BEGIN
    UPDATE counts SET count = count - 1 WHERE name = 'all';

    IF OLD.published = 1 THEN
        DELETE FROM videos_categories WHERE id_video = OLD.id;
        DELETE FROM videos_tags WHERE id_video = OLD.id;
    END IF;
  END;
|
delimiter ;

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= OLD.id;
    END IF;
  END' at line 6

これは、最初のトリガーでアクティブにする2つのトリガーです。

delimiter |
CREATE TRIGGER count_delete_videos_tags AFTER DELETE ON videos_tags
  FOR EACH ROW BEGIN
    UPDATE tags SET count = count - 1 WHERE id = OLD.id_tag;
  END;
|
delimiter ;


delimiter |
CREATE TRIGGER count_delete_videos_categories AFTER DELETE ON videos_categories
  FOR EACH ROW BEGIN
    UPDATE categories SET count = count - 1 WHERE id = OLD.id_category;

    IF OLD.id_category <> 20 AND OLD.id_category <> 34 THEN
        UPDATE counts SET count=count-1 WHERE name='english';
    ELSEIF OLD.id_category = 34 THEN
        UPDATE counts SET count=count-1 WHERE name='german';
    ELSEIF OLD.id_category = 20 THEN
        UPDATE counts SET count=count-1 WHERE name='italian';
    END IF;
  END;
|
delimiter ;

しかし、これは完璧に機能します

delimiter |
    CREATE TRIGGER count_delete_videos BEFORE DELETE ON videos
      FOR EACH ROW BEGIN
        UPDATE counts SET count = count - 1 WHERE name = 'all';

        IF OLD.published = 1 THEN
            DELETE FROM videos_categories WHERE id_video = OLD.id;
        END IF;
      END;
    |
    delimiter ;

Query OK, 0 rows affected (0.16 sec)

最初のトリガーを機能させるにはどうすればよいですか?私は何を間違っているのですか?助けてくれてありがとう。

13
Alex Prut

私の知る限り、両方のトリガーは問題ありませんが、次のことを試してみてください。

DELIMITER $$
CREATE TRIGGER count_delete_videos BEFORE DELETE ON videos
FOR EACH ROW 
BEGIN
  UPDATE counts SET count = count - 1 WHERE name = 'all';

  IF OLD.published = 1 THEN BEGIN
    DELETE FROM videos_categories WHERE id_video = OLD.id;
    DELETE FROM videos_tags WHERE id_video = OLD.id;
  END; END IF;
END$$

DELIMITER ;