MySQL在更新中对同一行进行多次减去
我有一个评论表和一个帖子表
每当删除帖子时,都会运行一个查询,从每个用户的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要存储计数,请使用:
...或:
当您可以执行一次操作时,依赖两条记录进行两次减法是没有意义的。
我不喜欢存储这些值,因为它们可以根据记录进行计算,而无需保持计数同步的麻烦。 视图可能是一个更好的主意......
If you're going to store the count, use:
...or:
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...