簡體   English   中英

如何選擇最大計數的行進行分組

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

我有一個表posts列( iduser_namethread_id )。
用戶可以為一個線程提交多個帖子。 發布線程是一對多的。

我需要找出誰每個線程最多提交了帖子。 因此結果將是Max(Count)user_namethread_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其中包含字段iduser_namethread_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM