mysql触发错误有2个条件

时间:2013-06-26 08:01:30

标签: mysql triggers conditional-statements

我想添加一个后插入触发器,它将执行以下操作。

第一个IF条件正常工作,但是当第二个IF条件停止时。

有什么想法吗?

USE `Syslog`;
DELIMITER $$

CREATE TRIGGER `SystemEventsR_AINS` AFTER INSERT ON SystemEventsR FOR EACH ROW

IF 
(exists
(select syslogtag from SystemEventsRcounter where syslogtag=
new.syslogtag) 

AND

(select simpledate from SystemEventsRcounter
where syslogtag=new.syslogtag)=new.simpledate) 

THEN
UPDATE SystemEventsRcounter 
SET records=records+1
WHERE SystemEventsRcounter.syslogtag=new.syslogtag;

ELSE INSERT SystemEventsRcounter (simpledate, syslogtag, records) values (new.simpledate,new.syslogtag,1);
END IF

1 个答案:

答案 0 :(得分:1)

<强>已更新

您需要的是INSERT INTO ... ON DUPLICATE KEY

CREATE TRIGGER `SystemEventsR_AINS` 
AFTER INSERT ON SystemEventsR 
FOR EACH ROW
    INSERT INTO SystemEventsRcounter (simpledate, syslogtag, records) 
    VALUES (NEW.simpledate, NEW.syslogtag, 1)
    ON DUPLICATE KEY UPDATE records = records + 1;

为了使它能够工作,你需要在(simpledate,syslogtag)上创建一个唯一的复合索引

CREATE UNIQUE INDEX idx_u_simpledate_syslogtag
ON SystemEventsRcounter (simpledate, syslogtag);

这是 SQLFiddle 演示。

如果您想按自己的方式使用,那么它可能会像

一样
DELIMITER $$
CREATE TRIGGER `SystemEventsR_AINS` 
AFTER INSERT ON SystemEventsR 
FOR EACH ROW
BEGIN
    IF ( 
          SELECT COUNT(*) simpledate 
            FROM SystemEventsRcounter 
           WHERE syslogtag  = NEW.syslogtag
             AND simpledate = NEW.simpledate
       ) > 0 THEN
        UPDATE SystemEventsRcounter 
           SET records = records + 1
        WHERE SystemEventsRcounter.syslogtag = NEW.syslogtag;
    ELSE 
        INSERT INTO SystemEventsRcounter (simpledate, syslogtag, records) 
        VALUES (NEW.simpledate, NEW.syslogtag, 1);
    END IF;
END$$
DELIMITER ;

这是 SQLFiddle 演示。