添加触发器的正确语法
Posted
技术标签:
【中文标题】添加触发器的正确语法【英文标题】:Right syntaxis for add trigger 【发布时间】:2014-02-10 15:06:03 【问题描述】:代码:
# 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
请告诉我如何正确添加触发器?
【问题讨论】:
【参考方案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 ;
【讨论】:
哦,抱歉,我没看到,我认为*
或 ''
中的错误。非常感谢和抱歉。
现在我得到第二个错误(#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
)。请看代码pastebin.com/gSr70eci【参考方案2】:
试试看:
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
【讨论】:
以上是关于添加触发器的正确语法的主要内容,如果未能解决你的问题,请参考以下文章