如果条件显示语法错误,请在内部声明-MYSQL触发器

问题描述

我尝试在插入之前使用触发器更新某些列

  DROP TRIGGER IF EXISTS update_p_posts_places;
DELIMITER $$
CREATE TRIGGER update_p_posts_places BEFORE
INSERT
ON
    `p_posts` FOR EACH ROW
BEGIN      
    DECLARE
        p_post_group_id_ int;
    SELECT
        `p_post_subgroup`.`p_post_group_id`
    INTO
        p_post_group_id_
    FROM
        `p_post_subgroup`
    WHERE
        `p_post_subgroup`.`p_post_subgroup_id` = NEW.p_post_subgroup_id;
        IF(p_post_group_id_ = 5) THEN
        BEGIN
        DECLARE
            place1_id_ int;
            place2_id_ int;
            place3_id_ int;
            place4_id_ int;
            place5_id_ int;
        SELECT
            `Places`.`place1_id`,`Places`.`place2_id`,`Places`.`place3_id`,`Places`.`place4_id`,`Places`.`place5_id`
        INTO
            place1_id_,place2_id_,place3_id_,place4_id_,place5_id_
        FROM
            `Places`
        WHERE
            `Places`.`place5_id` = NEW.p_post_place_id LIMIT 1;
    SET NEW.place5_id = place5_id_;
    SET NEW.place1_id = place1_id_;
    SET NEW.place2_id = place2_id_;
    SET NEW.place3_id = place3_id_;
    SET NEW.place4_id = place4_id_;
    END $$
    ELSE
SET NEW.place5_id = NULL;
END IF;
END $$
DELIMITER ;

显示了一些语法错误

#1064-您的sql语法有误;查看与您的MysqL服务器版本相对应的手册,以在'DECLARE附近使用正确的语法 place1_id_ int; place2_id_ int; '在第20行

解决方法

这是一个有效的触发器。我测试过在MySQL 5.7上创建它。

CREATE TRIGGER update_p_posts_places BEFORE INSERT ON `p_posts`
FOR EACH ROW
BEGIN      
    -- all declarations must be before any other statements
    DECLARE p_post_group_id_,place1_id_,place2_id_,place3_id_,place4_id_,place5_id_ int;
    SELECT
        `p_post_subgroup`.`p_post_group_id`
    INTO
        p_post_group_id_
    FROM
        `p_post_subgroup`
    WHERE
        `p_post_subgroup`.`p_post_subgroup_id` = NEW.p_post_subgroup_id;
    IF(p_post_group_id_ = 5) THEN
        SELECT
            `Places`.`place1_id`,`Places`.`place2_id`,`Places`.`place3_id`,`Places`.`place4_id`,`Places`.`place5_id`
        INTO
            place1_id_,place5_id_
        FROM
            `Places`
        WHERE
            `Places`.`place5_id` = NEW.p_post_place_id LIMIT 1;
        SET NEW.place5_id = place5_id_;
        SET NEW.place1_id = place1_id_;
        SET NEW.place2_id = place2_id_;
        SET NEW.place3_id = place3_id_;
        SET NEW.place4_id = place4_id_;
    ELSE
        SET NEW.place5_id = NULL;
    END IF;
END $$

您可以对多个局部变量使用一个DECLARE,但是您必须像var1,var2,var3,... int一样使用。换句话说,仅在类型末尾命名一次。请参阅文档:https://dev.mysql.com/doc/refman/8.0/en/declare-local-variable.html

BEGIN..END内不需要IF,并且绝对不要在最后一个$$之后使用END,因为这将终止解析器对整个CREATE TRIGGER的解释声明尚未完成。