samJL
samJL

Reputation: 737

MySQL subtracting multiple times for same row in update

I have a table of comments and a table of posts

Whenever a post is deleted, a query runs to subtract the number of comments (that are deleted later) from each user's comment_count

So if a user has 2 comments in a post, and that post is deleted, their balance should have 2 subtracted from it

My query is as follows:

    UPDATE users 
INNER JOIN comment ON users.id = comment.author 
       SET comment_count = comment_count - 1 
     WHERE comment.post = 1

User A has 2 comments with .post = 1, but for some reason that user only gets comment_count subtracted by 1 once, when it should happen twice

I think my syntax is right because when I:

    SELECT * 
      FROM users 
INNER JOIN comment ON users.id = comment.author 
     WHERE comment.post = 1

I get two results for user A

Shouldn't UPDATE be iterating over those two results, subtracting each time?

Can someone explain what I am missing? thank you

Upvotes: 0

Views: 1165

Answers (1)

OMG Ponies
OMG Ponies

Reputation: 332591

If you're going to store the count, use:

UPDATE USERS
   SET comment_count = (SELECT COUNT(*)
                          FROM COMMENT c
                         WHERE c.author = USERS.id)

...or:

UPDATE USERS u
  JOIN (SELECT c.author,
               COUNT(*) AS numComments
          FROM COMMENT c
      GROUP BY c.author) x ON x.author = u.id
   SET comment_count = x.numComments

There's no point in relying on two records to subtract twice, when you could perform the operation once.

I prefer not to store such values, because they can be calculated based on records without the hassle of keeping the counts in sync. A view might be a better idea...

Upvotes: 1

Related Questions