我需要向用户显示最多评论。我有两张桌子:
表:用户
ID | USERNAME | EMAIL
------------------------------
1 | USER01 | EMAIL01
2 | USER02 | EMAIL02
3 | USER03 | EMAIL03
4 | USER04 | EMAIL04
表:评论
ID | AUTHOR | COMMENT
----------------------------------
1 | USER01 | COMMENT...
2 | USER02 | COMMENT...
3 | USER01 | COMMENT...
4 | USER03 | COMMENT...
在这个示例中,user01
的评论最多,但我要说的是,我必须根据他们的评论计算结果。而且结果我必须向用户显示存储在Users表中的电子邮件。
我如何计算并同时检查两个表以返回结果?或者我应该首先获取用户信息然后计算?
答案 0 :(得分:3)
下面的查询处理具有最多评论次数的重复行
SELECT a.userName
FROM Users a
INNER JOIN Comments b
ON a.username = b.author
GROUP BY a.userName
HAVING COUNT(*) =
(
SELECT MAX(totalCount)
FROM
(
SELECT author, COUNT(*) totalCount
FROM comments
GROUP BY author
) a
)
但如果您不想处理,可以使用ORDER BY
和LIMIT
SELECT a.userName, COUNT(*) totalCount
FROM Users a
INNER JOIN Comments b
ON a.username = b.author
GROUP BY a.userName
ORDER BY totalCount DESC
LIMIT 1
答案 1 :(得分:2)
select username,email,count(*) as cnt
from users, comments
where author = username
group by username
order by cnt desc
limit 1