MySQl - 通过计算其他表中的数据来更新字段
有两张桌子。一种是用户信息“用户”,一种是评论信息“评论”。
我需要在用户表中创建新字段“评论”,其中包含该用户的评论数量。表“评论”有“用户”字段,其中包含该评论的用户 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你为什么要把它存储在那里?
为什么不直接显示组合查询呢?
如果您想按照自己的方式进行操作,请包含
到存储评论的脚本中。
并
进入用户可以删除评论的地方。否则,当用户添加新的comnts并且您尚未运行脚本时,您的数据可能会不同步。
Why do you want to store it there anyway?
Why not just show it combined query?
If you want to do it your way then include
into the script where you store the comment.
And
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.
是的,这是可能的。
这称为
表连接
。您无需将其他字段添加到
users
表中,而是添加到resulting
表中。这种查询正是关系数据库的发明目的。不要将其恢复为纯文本文件状态。这样做的原因有很多。
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 theresulting
table.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