使用触发器在表上执行插入或更新

时间:2013-07-10 19:03:54

标签: mysql sql triggers database

我试图从php页面获取一些值并在mysql数据库中执行触发器。具体如下:

DELIMITER $$

DROP TRIGGER /*!50032 IF EXISTS */ `test`.`MysqlTrigger`$$

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `MysqlTrigger` AFTER INSERT OR UPDATE ON `table2` 
    FOR EACH ROW BEGIN
    IF(NEW .flag=0) THEN
    INSERT INTO temp(sent,pcount,ncount) VALUES (NEW.sent,NEW.pcount,NEW.ncount);
    ELSE
        UPDATE temp SET pcount=NEW.pcount AND ncount=NEW.ncount WHERE id = NEW.id;
    END IF; 
    END;
$$

DELIMITER ;

哪个出错:

error Code : 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 'or update ON `table2` 
    FOR EACH ROW BEGIN
    if(NEW .flag=0) then
    INSERT INTO' at line 3

我尝试更改= with =:但错误仍然存​​在。有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您无法同时为更新插入定义触发器。您必须定义2个触发器:

CREATE TRIGGER `Mysql_insert_Trigger` AFTER INSERT ON `table2` ...
CREATE TRIGGER `Mysql_update_Trigger` AFTER UPDATE ON `table2` ...

答案 1 :(得分:0)

我算数了。语法有问题。这是正确的,它在不同的表和同一个表上的update-inset中同时执行更新插入但是使用if else:

DELIMITER $$

DROP TRIGGER /*!50032 IF EXISTS */ `test`.`MysqlTrigger2`$$

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `MysqlTrigger2` AFTER INSERT ON `table2` 
    FOR EACH ROW BEGIN
    IF 'flag'=1 THEN
        UPDATE record SET sent=NEW.sent WHERE id=NEW.id;
    ELSE
        INSERT INTO record VALUES (id,NEW.sent);
        INSERT INTO temp VALUES ()
    END IF;
    END;
$$

DELIMITER ;