我有两个表'testing1',其中包含字段'firstname'和'lastname'。另一个表'testing2',字段'firstname'。
因此触发器首先检查'testing2'表中是否存在'NEW.firstname'。如果确实如此,则它不执行INSERT查询但如果它不存在则执行INSERT查询并在'testing2'表中添加'NEW.firstname'。
这是我创建的触发器......但我在IF循环中遇到错误......
DELIMITER $$;
CREATE TRIGGER testRef AFTER INSERT ON testing1
FOR EACH ROW
BEGIN
DECLARE rowCount INTEGER;
SET @rowCount := ( SELECT COUNT(firstname) FROM testing2 WHERE testing2.firstname = NEW.firstname );
IF (rowCount)
INSERT INTO testing2 (firstname) VALUES (NEW.firstname);
END $$
我无法弄清楚我在哪里弄错了......有任何帮助吗?
答案 0 :(得分:0)
尝试
DELIMITER $$;
CREATE TRIGGER testRef AFTER INSERT ON testing1
FOR EACH ROW
BEGIN
DECLARE rowCount INTEGER;
SET @rowCount := ( SELECT COUNT(firstname) FROM testing2 WHERE testing2.firstname = NEW.firstname );
IF (rowCount) THEN
INSERT INTO testing2 (firstname) VALUES (NEW.firstname);
END IF;
END$$
DELIMITER ;
但也许你应该使用IF(rowCount)> 0
答案 1 :(得分:0)
这对我有用:
DELIMITER //
CREATE TRIGGER testRef AFTER INSERT ON testing1
FOR EACH ROW
BEGIN
DECLARE rowCount INTEGER;
SELECT COUNT(firstname) FROM testing2 WHERE testing2.firstname = NEW.firstname INTO rowCount;
IF rowCount = 0 THEN
INSERT INTO testing2 (firstname) VALUES (NEW.firstname);
END IF;
END //
DELIMITER ;