MYSQL触发器仅在至少运行两次后才更新

时间:2017-04-06 15:35:05

标签: mysql sql

我的问题是,我有触发器有效。我有2张桌子:

  • 节点
  • 表B

触发器内部的查询工作正常,所以我认为我搞砸了触发器,我不知道我做错了什么(之前从未使用过MySQL,所以它对我来说是一个猜谜游戏)

每当我删除tableb和node表,并插入节点时,只有当我再次插入节点时,新值才会被计入tableb。一切正常。我的MySQL触发器如下:

DELIMITER //
  CREATE TRIGGER INSERT_USERS_FORUM 
  AFTER INSERT ON node
  FOR EACH ROW BEGIN

update tableb
set forum_count =  (select count(*) from node n, forum_index fi
     where n.nid = fi.nid   and fi.tid = 18
     and n.uid = new.uid
     group by n.uid)
where UID = new.uid;
END//

任何帮助都表示赞赏,提前谢谢

1 个答案:

答案 0 :(得分:1)

By setting a unique key on uid in tableb, and using INSERT INTO ... ON DUPLICATE KEY UPDATE, you can ensure that a row exists in tableb to hold the forum count.

DELIMITER //

CREATE TRIGGER INSERT_USERS_FORUM 
AFTER INSERT ON node
FOR EACH ROW BEGIN
    INSERT INTO `tableb`
    (`forum_count`)
    VALUES
    ((select count(*) from `node` n, `forum_index` fi
         where n.nid = fi.nid   and fi.tid = 18
         and n.uid = new.uid
         group by n.uid))
    ON DUPLICATE KEY UPDATE `forum_count` =  (select count(*) from `node` n, `forum_index` fi
         where n.nid = fi.nid   and fi.tid = 18
         and n.uid = new.uid
         group by n.uid)
    where `UID` = new.`uid`;
END//

DELIMITER ;