[英]MySQl - update field by counting data in other table
有两个表。 一种是用户信息“用户”,一种是评论信息“评论”。
我需要在用户表中创建新字段“ comments”,其中包含该用户的评论数。 表“ comments”具有“ user”字段,其中包含该评论的用户ID。
到目前为止,计算每个用户的评论数的最佳方法是什么?
使用php时,您应该编写脚本来选择每个用户,然后计算其评论数,然后更新“评论”字段。 对我来说并不难,但很无聊。
是否可以不使用php而仅在MySQL中进行?
UPDATE TABLE users SET CommentCount = (SELECT COUNT(*) FROM comments WHERE AuthorUserId = users.id)
您为什么仍然要将它存储在那里? 为什么不只显示组合查询呢?
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
用户可以删除其评论的地方。 否则,当用户添加新命令并且您尚未运行脚本时,您的数据可能会不同步。
对的,这是可能的。 这称为table joining
。 您无需将其他字段添加到users
表,而是要添加到resulting
表。
SELECT users.*, count(comments.id) as num_comments
FROM users,comments
WHERE comments.cid=users.id
GROUP BY users.id
这样的查询就是发明relational databases
的目的。 不要将其还原为纯文本文件状态。 这样做有很多原因。
http://en.wikipedia.org/wiki/Database_normalization <-可读的好文字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.