5

I have two MySQL tables. A votes table (id, userId, postId, voteTypeId), and a posts table (id, postTypeId, userId, parentId) table. I'm writing a trigger that fires after insert on votes.

I would like the trigger to update a post in the posts table. But this post is not the same one referenced in my votes table under postId; It is the parent of that post.

BEGIN
CASE NEW.voteTypeId
    WHEN 2 THEN UPDATE posts SET posts.acceptedAnswerId = NEW.postId WHERE posts.id = @the parent postId of NEW.postId
    ELSE
        BEGIN
        END;
    END CASE;
END

I tried using this instead of @the parent of... :

(SELECT posts.parentId FROM posts WHERE posts.id = NEW.postId)

But you I don't think you can do SELECTS in triggers unless you use some type of SELECT INTO syntax. My only reference to the parent post that I want to update is its child postId in referenced in votes. So I don't know how to do the update without grabbing the right id through a select.

Is this possible?

2
  • You can in fact do a SELECT within a trigger. Your other syntax however looks a bit off. Commented Feb 4, 2011 at 16:10
  • @Mchl, I tried a few combinations, but it didn't work. Can you point me to what I'm doing wrong? Commented Feb 4, 2011 at 16:35

1 Answer 1

2

I'd do it like that:

BEGIN
  IF (NEW.voteTypeId = 2) THEN
    UPDATE
      posts AS p
    CROSS JOIN
      posts AS p2
    ON
      p.id = p2.parentId
    SET
     p.acceptedAnswerId = NEW.postId
    WHERE
     p2.id = NEW.postId;
  END IF;
END
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for that. Can I just ask you why you use a cross join? Why not just a normal join with an alias?
In MySQL INNER JOIN and CROSS JOIN and JOIN are all equivalent. Actually, according to ANSI SQL specification, I should have used INNER JOIN here (because I used ON join condition instead of USING()). Functionally it makes no difference, but potentially omproves portability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.