我有一个表posts
,其中包含列(id
,user_name
,thread_id
)。
用户可以为线程提交多个帖子。帖子的帖子是一对多的。
我需要找出每个帖子提交了最多帖子的人。结果就是这样
Max(Count)
,user_name
,thread_id
每个thread_id只有一行。
表太大了,所以我希望尽可能地优化查询。
答案 0 :(得分:3)
您可以尝试使用group by
和having
条款:
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
包含字段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;
它只返回一行...