如何检索mysql中所有记录的树节点数?

时间:2013-06-12 01:05:27

标签: mysql tree

我有这个mysql查询:

`select a.ID, a.parentID, a.name,
count(distinct b.ID) as level1,
count(distinct c.ID) as level2,
count(distinct d.ID) as level3,
count(distinct e.ID) as level4,
count(distinct f.ID) as level5,
count(distinct g.ID) as level6,
count(distinct h.ID) as level7,
count(distinct i.ID) as level8,
count(distinct j.ID) as level9,
count(distinct k.ID) as level10
from members a
left join members b on b.parentID = a.ID
left join members c on c.parentID = b.ID
left join members d on d.parentID = c.ID
left join members e on e.parentID = d.ID
left join members f on f.parentID = e.ID
left join members g on g.parentID = f.ID
left join members h on h.parentID = g.ID
left join members i on i.parentID = h.ID
left join members j on j.parentID = i.ID
left join members k on k.parentID = j.ID
left join members l on l.parentID = k.ID
where a.ID = 1`

如何更新此查询以允许在成员表中获取所有ID,而不仅仅是在当时检索1个查询结果。 我想替换a.ID = 1的地方,例如:

`where a.id IN (select ID from members)`

问题是,当我这样做时,我只得到一行所有计数分组。我想在ID列表中获取级别列表。

结果如下:

`ID | parent | name        | lv1 | lv2 | lv3 | lb4 | lv5 | lv6 | lv7 | lv8 | lv9 | lv10 |`
`1  | 0      | Manish Shah | 3   | 9   | 27  | 81  | 36  | 0   | 0   | 0   | 0   | 0    |`

我想要

`ID | parent | name        | lv1 | lv2 | lv3 | lb4 | lv5 | lv6 | lv7 | lv8 | lv9 | lv10 |`
`1  | 0      | Manish Shah | 3   | 9   | 27  | 81  | 36  | 0   | 0   | 0   | 0   | 0    |`
`2  | 4      | luiset Shah | 3   | 9   | 27  | 81  | 36  | 0   | 0   | 0   | 0   | 0    |`
`3  | 8      | sarah kanna | 3   | 9   | 27  | 81  | 36  | 0   | 0   | 0   | 0   | 0    |`

依旧......

2 个答案:

答案 0 :(得分:1)

您需要对数据进行分组,即

WHERE a.id IN (2341,2342,2343,2344)
GROUP BY a.id

答案 1 :(得分:0)

如果您想要所有成员,可以放弃WHERE条款,但需要GROUP BY a.ID