我有这样的桌子。
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
感谢帮助!
最佳答案
试试这个例子。根据需要添加更多列。
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
关于mysql - 计算值等于行ID的列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32106132/