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

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

【讨论】:

以上是关于添加触发器的正确​​语法的主要内容,如果未能解决你的问题,请参考以下文章

另一个 04079:无效的触发器规范

Oracle 语法错误触发器

如果存在 MySQL 触发器语法错误

Phpmyadmin 在“END”附近创建触发器语法错误

创建 SQL 触发器以更新另一个表时出错

我可以使用MySQL触发器更新刚添加的行吗?