MySQL在更新中对同一行进行多次减去

发布于 2024-09-30 01:48:11 字数 646 浏览 0 评论 0原文

我有一个评论表和一个帖子表

每当删除帖子时,都会运行一个查询,从每个用户的 comment_count 中减去评论数(稍后删除)

因此,如果用户在帖子中有 2 条评论,并且该帖子被删除,他们的余额应该从中减去 2

我的查询如下:

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

用户 A 有 2 条评论,.post = 1,但由于某种原因,用户只得到 comment_count 减去 1 一次,当它应该发生两次时,

我认为我的语法是正确的,因为当我:

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

我得到用户 A 的两个结果

时,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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只怪假的太真实 2024-10-07 01:48:11

如果要存储计数,请使用:

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

...或:

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

当您可以执行一次操作时,依赖两条记录进行两次减法是没有意义的。

我不喜欢存储这些值,因为它们可以根据记录进行计算,而无需保持计数同步的麻烦。 视图可能是一个更好的主意......

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文