【问题标题】:Counting all childs and sub-childs of each node in a hierarchy计算层次结构中每个节点的所有子节点和子节点
【发布时间】:2015-03-28 21:27:12
【问题描述】:

我有这种表层次结构:

 Table A
 |
 | Table B
   |
   | Table C
     |
     | Table D

对于Table A 中的给定行,假设带有ID=1 的行,我想得到这个输出:

ID  |  childB | ChildC | childD
-------------------------------
1   |    x    |   x    | x          

其中childBTable B 中的孩子数量,ChildCTable C 中的孩子在Table B...中找到的孩子的数量,等等。

我想通过一个 sql 查询得到这个输出。现在我只能使用这个查询来计算Table B 中孩子的数量:

SELECT  a.ID,  (SELECT 
                COUNT(b.parentID) 
                FROM TableB AS b 
                WHERE b.parentID= a.ID) 
                AS childB
FROM TableA a
WHERE a.ID =1

【问题讨论】:

  • 显示你的表结构,每个父子表之间的公共字段是什么!?看来您在所有这些表之间都有一个共同的 ID,这是不正确的
  • @Farhęg 不,我在所有这些表之间没有共同的 ID。每个表都有一个父 id 字段。
  • 我不是指ALL之间,如果每个表都有一个父id字段那么为什么你加入了基于ID b.ID= a.ID的base并且没有提到parentid?跨度>

标签: mysql sql count hierarchy


【解决方案1】:

如果您希望它用于特定 ID(如您提到的,例如 ID=1),您可以在 idparentid 上使用 left join 并使用 count(distinct)

select a.ID,
       count(distinct b.id) childB,
       count(distinct c.id) childC,
       count(distinct d.id) childD
from      tableA a 
left join tableB b on b.parentID = a.ID
left join tableC c on c.parentID = b.ID
left join tableD d on d.parentID = c.ID
where a.ID=1
group by a.ID;

这是一个小提琴DEMO

【讨论】:

    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多