1

我想展示帖子数量最多的 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 而不是只有一个,如何?

4

1 回答 1

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
于 2013-08-25T22:08:31.510 回答