如何选择具有最大计数的行

时间:2015-08-25 14:56:03

标签: mysql sql

我有一个表posts,其中包含列(iduser_namethread_id)。
用户可以为线程提交多个帖子。帖子的帖子是一对多的。

我需要找出每个帖子提交了最多帖子的人。结果就是这样 Max(Count)user_namethread_id每个thread_id只有一行。

表太大了,所以我希望尽可能地优化查询。

4 个答案:

答案 0 :(得分:3)

您可以尝试使用group byhaving条款:

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 )

答案 1 :(得分: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
)

没有limit的系统的简易解决方法是:

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
)

答案 2 :(得分:0)

试试这个.. SELECT p.user_name,p.thread_id  从后p   GROUP BY p.user_name,p.thread_id   有COUNT(p.thread_id)=   (SELECT MAX(threadtypecount)     FROM(SELECT thread_id,COUNT([user_name])AS threadtypecount            从邮寄            GROUP BY thread_id)T1)

希望这会有所帮助..

答案 3 :(得分:0)

假设您的表格posts包含字段iduser_name和& thread_id。 如果您想查询哪个用户在特定帖子上发布了最多帖子以及从表中发布了他的帖子总数,您可以使用此MySQL查询来实现:

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;

它只返回一行...