문제

I want to show the 5 threads with highest number of posts, but im kinda broken and I cant even imagine how to do it

the SQL tables are like this, of course is just an example

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

I want the result to be like this

thread3
thread2
thread1

I should do a separate query?, I mean 2 instead of only one, how?

도움이 되었습니까?

해결책

You need to join the table to itself, with the main thread row in the first side of the join and the post rows in the other side:

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top