2015-08-19 56 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

啊!谢谢! :) –