2013-08-25 115 views
1

我想顯示5個線程與職位的人數最多,但即時通訊有點壞,我甚至無法想象該怎麼辦呢伯爵表在一列相同的ID,並顯示最高

的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而不是隻有一個,怎麼樣?

回答

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 
+0

你的意思與T1和T2? –

+0

好吧,我想你是指另一個表或什麼,一切都在同一個地方http://i.imgur.com/EzNwCVM.png(忽略內容,它只是爲了測試),第一個結果必須是ID 8(線程8)與主題'qweeqweqwqew',第二個結果必須是ID 5(線程5) –

+0

T1和t2是您的表的「別名」(我簡單地稱爲mytable,因爲你沒有說什麼表名是),當將表聯接到自己時需要這樣,所以可以明確地引用表的不同實例的列。 – Bohemian