简体   繁体   English

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

[英]MySQl - update field by counting data in other table

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. 我需要在用户表中创建新字段“ comments”,其中包含该用户的评论数。 Table "comments" has "user" field with user's id of that comment. 表“ comments”具有“ user”字段,其中包含该评论的用户ID。

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. 使用php时,您应该编写脚本来选择每个用户,然后计算其评论数,然后更新“评论”字段。 It is not hard for me, but boring. 对我来说并不难,但很无聊。

Is it possible to do it without php, only in MySQL? 是否可以不使用php而仅在MySQL中进行?

UPDATE TABLE users SET CommentCount = (SELECT COUNT(*) FROM comments WHERE AuthorUserId = users.id)

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. 否则,当用户添加新命令并且您尚未运行脚本时,您的数据可能会不同步。

Yes, it is possible. 对的,这是可能的。 This is called table joining . 这称为table joining You don't add another field to the users table, but to the resulting table. 您无需将其他字段添加到users表,而是要添加到resulting表。

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. 这样的查询就是发明relational databases的目的。 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 http://en.wikipedia.org/wiki/Database_normalization <-可读的好文字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM