5
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

From this query I want to get the display_name for the person with the highest count of comments. Any guidance is appreciated.

2 Answers 2

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
    )
Sign up to request clarification or add additional context in comments.

4 Comments

mind explaining HAVING COUNT(*) line to me? never really used it like that before
HAVING COUNT(*) works like a WHERE clause. But the main difference is that HAVING supports aggregate functions just like MAX, MIN, SUM, etc.. while WHERE won't.
Thanks, also this works within this scope, but I should have posted more of the query which it is nested in. Throwing an error now
Oh nevermind, it was my mistake had left out a column reference. Thanks again @JW.
0

I think the simplest way is just to sort your query and take the first row:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.