计数列,其中值等于行ID

时间:2015-08-19 21:42:02

标签: mysql sql

我有这样的表格。

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

感谢您的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你真的很接近,你只需要切换到标量子查询:

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