代码:
# 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
请告诉我如何正确添加触发器?
答案 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