计算列中具有相同ID的表并显示最高值

时间:2013-08-25 21:56:26

标签: mysql sql count self-join

我想展示帖子数量最多的5个帖子,但我有点破碎,我甚至无法想象如何做到这一点

SQL表是这样的,当然只是一个例子

id | thread | subject | body
________________________________________________________
1  | NULL   | Thread1 | this is the body of the first thread id1
2  | 1      | NULL    | post id2 in the first thread id1
3  | NULL   | Thread2 | this is the body of the 2nd thread id3
4  | 2      | NULL    | post id4 in the second thread id4
5  | 2      | NULL    | post id4 in the second thread id5
6  | NULL   | Thread3 | this is the body of the 3rd thread id6
7  | 6      | NULL    | post id4 in the third thread id7
8  | 6      | NULL    | post id4 in the third thread id8
9  | 6      | NULL    | post id4 in the third thread id9

我希望结果像这样

thread3
thread2
thread1

我应该做一个单独的查询?,我的意思是2而不是只有一个,怎么样?

1 个答案:

答案 0 :(得分:3)

您需要将表连接到自身,主要线程行位于连接的第一侧,而帖子行位于另一侧:

select t1.subject
from mytable t1
join mytable t2 on t2.thread = t1.id
where t1.thread is null
group by 1
order by count(*) desc
limit 5