MySQL 中的 IF 条件触发

Trigger with IF condition in MySQL

我的数据库触发器有问题(我使用的是 phpmyadmin)。当我在 table 'customer'.

中插入新行时
+-------------+------+------------+--------------+  
| id_customer | name |  group     |  subscribed  |  
+-------------+------+------------+--------------+  
|    1        | John | Business   |    true      |  
|    2        | Rose | Particular |    true      |    
|    3        | Ann  | Business   |    false     |    
+-------------+------+------------+--------------+  

我想在我的 table 'groups_customer'

中添加一个新行
+----------+-------------+  
| id_group | id_customer |  
+----------+-------------+  
|   3      |     1       |  
|   4      |     2       |  
+----------+-------------+

因此,如果我插入一个已订阅的新客户并使用组 'Business',它将在 'groups_customer' 中添加一行 id_group=3
如果是新订阅的 'Particular' 客户,它将添加 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 (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