0

我需要向用户展示最多的评论。我有两张桌子:

表:用户

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,评论最多,但可以说我必须用他们拥有的评论数来计算它们。而且结果我必须向用户显示存储在用户表中的电子邮件。

如何计算并同时检查两个表以返回结果?还是我应该先获取用户信息然后计数?

4

2 回答 2

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 BYLIMIT

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
于 2013-01-13T16:08:44.430 回答
2
select username,email,count(*) as cnt 
from users, comments 
where author = username 
 group by username
 order by cnt desc
 limit 1
于 2013-01-13T16:10:24.210 回答