简体   繁体   中英

How do I select a row with max count doing a group by

I have a table posts with columns ( id , user_name , thread_id ).
A user can submit multiple posts for a thread. thread to post is one to many.

I need to find out who submitted max posts per thread. So the result would be Max(Count) , user_name , thread_id WHERE there will be only one row per thread_id.

The table is too huge so I wanted to get the query optimized as much as I could.

You can try with the group by and having clauses:

select t.user_name, t.thread_id , count(*) as max_count
from tbl t
group by t.user_name, t.thread_id
having count(*) = ( select count(*) as ttl
                    from tbl
                    where thread_id = t.thread_id
                    group by user_name
                    order by ttl desc
                    limit 1 )
select user_name, thread_id, count(*) as max
from tbl t
group by user_name, thread_id
having count(*) = (
    select count(*) as cnt /* most posts per user per thread */
    from tbl
    group by user_name, thread_id
    order by cnt desc
    limit 1
)

Easy workaround for system that don't have limit is:

select user_name, thread_id, count(*) as max
from tbl t
group by user_name, thread_id
having count(*) = (
    select max(cnt) from (
        select count(*) as cnt /* most posts per user per thread */
        from tbl
        group by user_name, thread_id
    ) m
)

Try this.. SELECT p.user_name, p.thread_id FROM post p GROUP BY p.user_name,p.thread_id HAVING COUNT(p.thread_id) = (SELECT MAX(threadtypecount) FROM (SELECT thread_id, COUNT([user_name]) AS threadtypecount FROM post GROUP BY thread_id) T1)

hope this helps..

Suppose you have a table posts with fields id , user_name & thread_id . If you want to query which user has posted the most posts on a specific thread and the total number of his posts from a table, you can achieve that with this MySQL query:

SELECT user_name, thread_id, count(thread_id) 
FROM posts WHERE thread_id=1 GROUP BY user_name 
ORDER BY count(thread_id) DESC LIMIT 1;

It will return only one row...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM