2015-08-19 59 views
0

我有這樣的表。計數列的值等於行ID

id | name | desc | parent 
------------------------- 
1 | abc | def | 0 
2 | abc | def | 1 
3 | abc | def | 1 
4 | abc | def | 1 
5 | abc | def | 2 
6 | abc | def | 3 

,我需要得到的是這一點,讓所有行數多少行parent同實際行的ID。而且所有的都必須按這個數量排序。

id | name | desc | parent | count 
------------------------- 
1 | abc | def | 0  | 3 
2 | abc | def | 1  | 1 
3 | abc | def | 1  | 1 
4 | abc | def | 1  | 0 
5 | abc | def | 2  | 0 
6 | abc | def | 3  | 0 

我這個結束了,但實際上它沒有工作:/

select c.pocet, a.* from posts a, (select count(*) as pocet from posts b where b.parent=a.id) c 

感謝您的幫助!

+0

你能添加什麼是對數據的給定的樣本,結果呢? – Chris

+0

你問的是如何計算每個家長有多少個孩子? –

+0

@lliev你有結果我需要在第一篇文章。 –

回答

1

試試這個例子。根據需要添加更多列。

select 
t.id,t.parent,coalesce(x.cnt,0) as cnt 
from t left join 
(select parent,count(*) as cnt 
from t 
group by parent) x 
on x.parent = t.id 

Fiddle

+0

這就是答案!非常感謝! –

0

你實際上是接近,你只需要切換到標量子查詢:

select a.*, 
    (select count(*) from posts b where b.parent=a.id) as pocet 
from posts a 
+0

啊!謝謝! :) –