[英]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.