如何正确进行查询触发?

时间:2014-01-20 20:12:19

标签: mysql sql triggers phpmyadmin

代码:

CREATE TRIGGER `TriggerUpdateNewsAfterChangeLikes` AFTER INSERT, UPDATE, DELETE ON `Likes`
FOR EACH ROW
BEGIN 
UPDATE `News` SET 
`CountUpLikes` = (SELECT COUNT(*) FROM `Likes` WHERE `NewsIdn` = OLD.`NewsIdn` AND `Type` = 'up'),
`CountDownLikes` = (SELECT COUNT (*) FROM `Likes` WHERE `NewsIdn` = OLD.`NewsIdn` AND `Type` = 'down'),
`CountFavorites` = (SELECT COUNT(*) FROM `Likes` WHERE `NewsIdn` = OLD.`NewsIdn` AND `IsFavorite` = 'yes');
END

当我进行查询时,在phpmyadmin中我收到错误:

#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 ' UPDATE ON `Likes`
FOR EACH ROW
BEGIN 
UPDATE `News` SET 
`CountUpLikes` = (' at line 1 

请告诉我为什么我会收到此错误以及如何正确查询?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

    CREATE TRIGGER TriggerUpdateNewsAfterChangeLikes AFTER UPDATE ON Likes
    FOR EACH ROW
    BEGIN 
    UPDATE News SET 
    CountUpLikes = (SELECT COUNT(*) FROM `Likes` WHERE `NewsIdn` = OLD.`NewsIdn` AND `Type` = 'up');
    UPDATE News SET
    CountDownLikes = (SELECT COUNT (*) FROM `Likes` WHERE `NewsIdn` = OLD.`NewsIdn` AND `Type` = 'down');
    UPDATE News SET
    CountFavorites = (SELECT COUNT(*) FROM `Likes` WHERE `NewsIdn` = OLD.`NewsIdn` AND `IsFavorite` = 'yes');
    END;

不幸的是,mysql不允许在同一个触发器上发生多个事件。