添加触发器的正确​​语法

时间:2014-01-21 06:46:07

标签: mysql sql phpmyadmin triggers

代码:

# Triggers for table Likes->News

CREATE TRIGGER `TriggerUpdateNewsAfterInsertLikes` AFTER INSERT ON `Likes`
FOR EACH ROW
BEGIN 
UPDATE `News` SET 
`CountUpLikes` = (SELECT COUNT(*) FROM `Likes` WHERE `NewsIdn` = NEW.`NewsIdn` AND `Type` = 'up'),
`CountDownLikes` = (SELECT COUNT (*) FROM `Likes` WHERE `NewsIdn` = NEW.`NewsIdn` AND `Type` = 'down'),
`CountFavorites` = (SELECT COUNT(*) FROM `Likes` WHERE `NewsIdn` = NEW.`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 '*) FROM `Likes` WHERE `NewsIdn` = NEW.`NewsIdn` 
AND `Type` = 'down'),
`CountFav' at line 8 

如果我使用id代替*,我会收到错误:

#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 '' at line 9

请告诉我如何正确添加触发器?

2 个答案:

答案 0 :(得分:1)

听起来令人难以置信,在mysql中,count(*)之间没有空格:

select count(*) -- OK
select count (*) -- syntax error!

在你的情况下,它在第二个子查询中。将其更改为:

...
`CountDownLikes` = (SELECT COUNT(*) FROM `Likes` WHERE `NewsIdn` = NEW.`NewsIdn` AND `Type` = 'down'),
...

这同样适用于cast(...),这是语法错误:cast (col as unsigned)(请注意cast(之间的空格)。我可以告诉你,我浪费了大约一个小时的时间来捕捉这颗小宝石。


编辑;

另一个错误可能是由于没有更改分隔符,如果在过程中有分号,则需要使用分隔符:

DELIMITER //

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

DELIMITER ;

答案 1 :(得分:0)

试一试:

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