【问题标题】:Trigger with IF condition in MySQL在 MySQL 中使用 IF 条件触发
【发布时间】:2016-01-22 18:40:48
【问题描述】:

我的数据库上的触发器有问题(我正在使用 phpmyadmin)。当我在表“客户”中插入新行时。

+-------------+------+------------+--------------+  
| id_customer | name |  group     |  subscribed  |  
+-------------+------+------------+--------------+  
|    1        | John | Business   |    true      |  
|    2        | Rose | Particular |    true      |    
|    3        | Ann  | Business   |    false     |    
+-------------+------+------------+--------------+  

我想在我的表“groups_customer”中添加一个新行

+----------+-------------+  
| id_group | id_customer |  
+----------+-------------+  
|   3      |     1       |  
|   4      |     2       |  
+----------+-------------+

因此,如果我插入一个已订阅的新客户并使用组“Business”,它将在 id_group=3 的“groups_customer”中添加一行
如果是新订阅的“特定”客户,它将添加 id_group=4
在任何其他情况下,它都不会在“groups_customer”上添加任何行

所以这是我的触发器:

CREATE TRIGGER register_client_group  
AFTER INSERT  
ON customer  
FOR EACH ROW  
BEGIN  
IF (NEW.`group`='Business' AND NEW.subscribed=true)  
THEN  
INSERT INTO groups_customer (id_group, id_customer) VALUES (3, NEW.id_customer);  
ELSE IF (NEW.`group`='Particular' AND NEW.subscribed=true)  
THEN  
INSERT INTO groups_customer (id_group, id_customer) VALUES (4, NEW.id_customer);  
END IF;  
END;  

MySQL 说:

"#1064 - 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 '' at line 8 "  

问题似乎出在 IF 语句上。

【问题讨论】:

  • group 是 mysql 中的保留字,您需要用反引号将其包装起来 ``

标签: mysql if-statement triggers phpmyadmin


【解决方案1】:

GROUP 是 MySQL 中的保留字 (used by the GROUP BY-Function)。

所以你的触发函数应该是:

CREATE TRIGGER register_client_group
AFTER INSERT
ON customer
FOR EACH ROW
BEGIN
    IF (NEW.`group`='Business' AND NEW.subscribed=true)  
    THEN
        INSERT INTO groups_customer (id_group, id_customer) VALUES (3, NEW.id_customer);  
    ELSEIF (NEW.`group`='Particular' AND NEW.subscribed=true)  
    THEN
        INSERT INTO groups_customer (id_group, id_customer) VALUES (4, NEW.id_customer);
    END IF;
END;

如果您使用的是 PHPmyadmin,请记住更改默认分隔符,如本图所示。 http://4.bp.blogspot.com/-u8TUx_srGrw/TVZp7saqF3I/AAAAAAAAIn8/fvYOaGcxNfY/s640/DELIMITER+MYSQL.jpg

【讨论】:

  • 没错,但还是报错:#1064 - 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 8 行的 '' 附近使用正确的语法 我认为这是 IF ELSE 语句的问题,但我不知道如何使其工作。
  • 我添加了一个;并将另一组放入`。其余的看起来不错,例如查看 mysql 文档:dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html
  • 我终于找到了解决方案。您的代码几乎是完美的,但您必须删除 ELSE IF 之间的空格(所以它是 ELSEIF),如果您使用 phpmyadmin 以便使用带有 BEGIN 和 END 语句的触发器,您必须更改默认分隔符,如在此图片。 4.bp.blogspot.com/-u8TUx_srGrw/TVZp7saqF3I/AAAAAAAAIn8/….
猜你喜欢
  • 2016-08-13
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
相关资源
最近更新 更多