我有一个表posts
的列(id
,user_name
,thread_id
)。
用户可以为一个线程提交多个帖子。发布线程是一对多的。
我需要找出谁每个线程最多提交了帖子。因此,其结果必然是Max(Count)
,user_name
,thread_id
哪里还会有每的thread_id只有一行。
该表太大,因此我想尽可能优化查询。
您可以尝试使用group by
andhaving
子句:
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 )
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句