1

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

第一个 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
4

1 回答 1

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演示。

于 2013-06-26T08:29:17.163 回答