SQL: TRIGGER and PROCEDURE

时间:2016-03-04 18:07:39

标签: sql stored-procedures triggers mariadb

I have a table «blog» with a list of items. I would like to add a column with the number of comments for every item. I would also this number to be automatically updated.

So, I've created a procedure:

DELIMITER |
CREATE PROCEDURE Procedure_comments()
BEGIN
UPDATE blog SET nb_comment = (SELECT COUNT(Comment.id) 
                              FROM Comment 
                              WHERE Comment.blog_id = blog.id);
END|

And I've tried to add a trigger which, in my mind would «launch» the procedure when inserting/deleting a comment:

CREATE TRIGGER trigger_nb_comments 
AFTER INSERT ON Comment 
FOR EACH ROW EXECUTE Procedure_comments()|

But… I got an error:

ERROR 1336 (0A000): Dynamic SQL is not allowed in stored function or trigger

So… How can I proceed to automatically update the number of comments on my main table «blog»?

Thanks a lot for your help.

1 个答案:

答案 0 :(得分:0)

每当用户插入评论时,您建议的触发器将为博客表中的每一行重新计算/更新nb_comment,并且不会处理评论删除。

而不是触发器,我建议使用简单的视图:

CREATE VIEW vw_blog
AS
SELECT b.id, b.title, b.body,
       COUNT(*)  AS nb_comment
FROM blog b
JOIN `Comment` c
  ON b.id = c.blog_id
GROUP BY b.id, b.title, b.body;

SqlFiddleDemo

输出:

╔═════╦════════════════════╦═══════════════════════════════════╦════════════╗
║ id  ║       title        ║               body                ║ nb_comment ║
╠═════╬════════════════════╬═══════════════════════════════════╬════════════╣
║  1  ║ SQL Server         ║ SQL Server...                     ║          3 ║
║  2  ║ MySQL performance  ║ To improve performance invest...  ║          1 ║
╚═════╩════════════════════╩═══════════════════════════════════╩════════════╝