如果条件匹配插入触发器后,MySQL插入查询

时间:2016-07-13 19:16:00

标签: mysql if-statement triggers insert

我正在使用带有MySQL版本的WampServer:5.7.9和phpMyAdmmin版本:4.5.2

如果Table2中不存在数据,我正在尝试在Table1上编写一个插入后触发器以在Table2中插入数据。以下是我的询问:

DROP TRIGGER IF EXISTS `insert_customer`;
CREATE TRIGGER `insert_customer` AFTER INSERT ON `installations`
FOR EACH ROW BEGIN
    IF (SELECT COUNT(*) FROM `customers` WHERE `customers`.`phone` = NEW.`phone`) = 0
    THEN INSERT INTO `customers` (`phone`, `imei`, `platform`, `version_code`) VALUES (NEW.`phone`, NEW.`imei`, NEW.`platform`, NEW.`version_code`);
    END IF;
END;

这给了我以下错误:

#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 4

我也尝试过分隔符:

DROP TRIGGER IF EXISTS `insert_customer`;
DELIMITER |
CREATE TRIGGER `insert_customer` AFTER INSERT ON `installations`
FOR EACH ROW BEGIN
    IF (SELECT COUNT(*) FROM `customers` WHERE `customers`.`phone` = NEW.`phone`) = 0
    THEN INSERT INTO `customers` (`phone`, `imei`, `platform`, `version_code`) VALUES (NEW.`phone`, NEW.`imei`, NEW.`platform`, NEW.`version_code`)
    END IF;
END;
|
DELIMITER ;

这给了我以下错误:

#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 'END IF;
END' at line 5

我在这里做错了什么?有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

我的猜测是额外的分隔符;尝试改变

END;
|

END|

答案 1 :(得分:0)

最后我得到了它。正确的SQL是:

DROP TRIGGER IF EXISTS `insert_customer`;
DELIMITER |
CREATE TRIGGER `insert_customer` AFTER INSERT ON `installations`
FOR EACH ROW BEGIN
    IF (SELECT COUNT(*) FROM `customers` WHERE `customers`.`phone` = NEW.`phone`) = 0 THEN
        INSERT INTO `customers` (`phone`, `imei`, `platform`, `version_code`) VALUES (NEW.`phone`, NEW.`imei`, NEW.`platform`, NEW.`version_code`);
    END IF;
END;|
DELIMITER ;

;在我的INSERT查询结束时解决了我的问题。 :d