Posted on November 24th, 2010
2098 views Our Triggers CREATE PROCEDURE count_comments (IN userId INT) BEGIN SET @numComments = (SELECT COUNT(*) FROM comments WHERE uid = userId); UPDATE users SET num_comments = @numComments WHERE uid = userId; END; This code shouldn't be much of a surprise to you. If it is I encourage you to read through my guide on MySQL stored routines. But a basic run down is in order anyways. On the first line we declare the procedure, nothing amazing here. You'll notice our one parameter, the user ID we're working with. It's an INT in the user table, so it's an INT here too. And we aren't outputting it, so it's of the type IN. Line three is where we collect the number of comments belonging to the given user ID. You should remember that the @ operator is how we reference variables in MySQL. Here we're setting the @numComments variable to be equal to the output from the SELECT query. That query will simply count the comments who have a uid of userId. And then of course we update the user's row accordingly. Remember that if you're on the command line you'll need to change your delimiter prior to writing the procedure, and then terminate it accordingly. Now that we've written the workhorse for the triggers, let's write the triggers themselves. Because they're nearly identical I am going to present them to you at once. We'll go through them afterwards. CREATE TRIGGER update_num_comments_on_insert AFTER INSERT ON comments FOR EACH ROW BEGIN CALL count_comments(NEW.uid); END; CREATE TRIGGER update_num_comments_on_delete AFTER DELETE ON comments FOR EACH ROW BEGIN That should all look fairly familiar to you now. We're giving our triggers descriptive names as they need to be unique and should be representative of what they're doing; or at least what they're reacting to. We're going with AFTER because we want to make sure that the action actually takes place; we're not interested in changing any of the incoming data.
|