使用if条件的Mysql触发器中的语法错误

时间:2016-05-11 09:44:20

标签: mysql

我想使用触发器更新两个表,所以我运行以下查询:

CREATE TRIGGER project_document_trig AFTER INSERT ON object_metadata
FOR EACH ROW 
BEGIN
   IF NEW.group like 'group1' THEN
       UPDATE documents as document
           SET document.projects_count = document.projects_count + 1
           WHERE document.id = NEW.value;
       UPDATE projects as project
           SET project.documents_count = project.documents_count + 1
           WHERE project.id = NEW.resource_id ;
   END IF
END

我收到语法错误

2 个答案:

答案 0 :(得分:2)

使用此代码并检查:

DELIMITER $$

CREATE TRIGGER project_document_trig 
AFTER INSERT ON object_metadata 
FOR EACH ROW 
BEGIN
   IF NEW.group like 'group1' THEN
       UPDATE documents as document
           SET document.projects_count = document.projects_count + 1
           WHERE document.id = NEW.value;
       UPDATE projects as project
           SET project.documents_count = project.documents_count + 1
           WHERE project.id = NEW.resource_id ;
   END IF;
END$$
DELIMITER ;

或者您可以使用:

DELIMITER $$

CREATE TRIGGER project_document_trig 
AFTER INSERT ON object_metadata 
FOR EACH ROW 
BEGIN
   IF (EXISTS(SELECT 1 FROM object_metadata WHERE NEW.group like 'group1'))
   THEN
       UPDATE documents as document
           SET document.projects_count = document.projects_count + 1
           WHERE document.id = NEW.value;
       UPDATE projects as project
           SET project.documents_count = project.documents_count + 1
           WHERE project.id = NEW.resource_id ;
   END IF;
END$$
DELIMITER ;

答案 1 :(得分:0)

只需在END IF

之后添加分号
END IF;