查询多个计数值

时间:2013-01-30 14:50:03

标签: mysql sql select count

SELECT  cm.commenter_id,
        cm.comment,
        m.id,
        (
            SELECT COUNT(*) AS r_count
            FROM comments
            GROUP BY comments.commenter_id
        ) AS count,
        m.display_name
FROM    comments cm
        INNER JOIN members m
            ON cm.commenter_id = m.id

从此查询中,我想获取具有最高评论数的人的display_name。任何指导都表示赞赏。

2 个答案:

答案 0 :(得分:3)

SELECT  m.id, m.display_name, COUNT(*) totalComments
FROM    comments cm
        INNER JOIN members m
            ON cm.commenter_id = m.id
GROUP   BY m.id, m.display_name
HAVING  COUNT(*) =
    (
        SELECT  COUNT(*) totalCount
        FROM    Comments
        GROUP   BY  commenter_id
        ORDER   BY totalCount DESC
        LIMIT 1
    )

答案 1 :(得分:0)

我认为最简单的方法就是对查询进行排序并占据第一行:

SELECT  cm.commenter_id,
        cm.comment,
        m.id,
        (
            SELECT COUNT(*) AS r_count
            FROM comments
            GROUP BY comments.commenter_id
        ) AS count,
        m.display_name
FROM    comments cm
        INNER JOIN members m
            ON cm.commenter_id = m.id
order by count desc
limit 1