[英]How do I select a row with max count doing a group by
我有一个表posts
列( id
, user_name
, thread_id
)。
用户可以为一个线程提交多个帖子。 发布线程是一对多的。
我需要找出谁每个线程最多提交了帖子。 因此结果将是Max(Count)
, user_name
, thread_id
,其中每个thread_id只有一行。
该表太大,因此我想尽可能优化查询。
您可以group by
having
子句来尝试使用该group by
:
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
)
对于没有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
)
试试这个。.选择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从发帖组(thread_id)发出的threadtypecount)T1)
希望这可以帮助..
假设您有一个表posts
其中包含字段id
, user_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;
它只会返回一行...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.