2016-07-13 107 views
0

我使用WampServer與MySQL版本匹配後:5.7.9和phpMyAdmmin版本:4.5.2MySQL的插入查詢,如果條件插入觸發

我想在表1 INSERT觸發器後寫一個插入表2中的數據如果數據不存在於表2中。下面是我的查詢:

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 

我在做什麼g在這裏?任何幫助?

+1

他們給出的錯誤是......?即使應用了您的建議, – Uueerdo

回答

0

我的猜測是額外的分隔符;嘗試改變

END; 
| 

END| 
+0

仍然會收到同樣的錯誤。 :( – Muntasir

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 ; 

The;在我的INSERT查詢結束時解決了我的問題。 :D