MySQl - 通过计算其他表中的数据来更新字段

发布于 2024-08-27 17:46:30 字数 237 浏览 1 评论 0原文

有两张桌子。一种是用户信息“用户”,一种是评论信息“评论”。

我需要在用户表中创建新字段“评论”,其中包含该用户的评论数量。表“评论”有“用户”字段,其中包含该评论的用户 ID。

到目前为止,计算每个用户评论数量的最佳方法是什么?

使用 php,您应该编写脚本来选择每个用户并计算他的评论数量,然后更新“评论”字段。对我来说并不难,但很无聊。

是否可以不使用 php,只使用 MySQL 来实现?

There are two tables. One is users info "users", one is comments info "comments".

I need to create new field "comments" in users table, that contains number of comments of that user. Table "comments" has "user" field with user's id of that comment.

What is optimal way to count number of comments by every user so far?

With php you should write script that selects every user and than count number of his comments and then update "comments" field. It is not hard for me, but boring.

Is it possible to do it without php, only in MySQL?

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

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

发布评论

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

评论(3

跨年 2024-09-03 17:46:30
UPDATE TABLE users SET CommentCount = (SELECT COUNT(*) FROM comments WHERE AuthorUserId = users.id)
UPDATE TABLE users SET CommentCount = (SELECT COUNT(*) FROM comments WHERE AuthorUserId = users.id)
落花随流水 2024-09-03 17:46:30

你为什么要把它存储在那里?
为什么不直接显示组合查询呢?

select users.name, count(comments.id) as comment_count
from users
join comments on users.id=comments.user_id
group by users.id

如果您想按照自己的方式进行操作,请包含

update users set comment=comment+1 where id=$user_id

到存储评论的脚本中。

update users set comment=comment-1 where id=$user_id

进入用户可以删除评论的地方。否则,当用户添加新的comnts并且您尚未运行脚本时,您的数据可能会不同步。

Why do you want to store it there anyway?
Why not just show it combined query?

select users.name, count(comments.id) as comment_count
from users
join comments on users.id=comments.user_id
group by users.id

If you want to do it your way then include

update users set comment=comment+1 where id=$user_id

into the script where you store the comment.

And

update users set comment=comment-1 where id=$user_id

into the place where user can delete his comment. Otherwise your data might be out of sync when user adds new commnts and you haven't run the script yet.

_失温 2024-09-03 17:46:30

是的,这是可能的。
这称为表连接
您无需将其他字段添加到 users 表中,而是添加到 resulting 表中。

SELECT users.*, count(comments.id) as num_comments 
FROM users,comments 
WHERE comments.cid=users.id 
GROUP BY users.id

这种查询正是关系数据库的发明目的。不要将其恢复为纯文本文件状态。这样做的原因有很多。
http://en.wikipedia.org/wiki/Database_normalization <-- 很好的文本读

Yes, it is possible.
This is called table joining.
You don't add another field to the users table, but to the resulting table.

SELECT users.*, count(comments.id) as num_comments 
FROM users,comments 
WHERE comments.cid=users.id 
GROUP BY users.id

Such a query is what relational databases were invented for. Do not revert it to the plain text file state. There is many reasons to make it that way.
http://en.wikipedia.org/wiki/Database_normalization <-- good text to read

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