MySql分层查询

问题描述

我有“组织”表:

Id  Name  ParentId
------------------
 1  Org1         5
 2  Org2         5
 3  Org3         4
 4  Depart2      6
 5  Depart1      6
 6  Company   null

我想实现的是返回表的查询 每个组织在层次结构树中都属于较高级别的组织单位:

Id    BelongsToOrgId
1     1                  Org1 is part of Org1
1     5                  Org1 is part of Depart1  
1     6                  Org1 is part of Company
2     2                  Org2 is part of Org2
2     5                  Org2 is part of Depart1
2     6                  Org2 is part of Company
3     3                  Org3 is part of Org3
3     4                  Org3 is part of Depart2
3     6                  Org3 is part of Company
4     4                  Depart2 is part of Depart2 
4     6                  Depart2 is part of Company 
5     5                  Depart1 is part of Depart1  
5     6                  Depart1 is part of Company
6     6                  Company is part of Company

最好的问候, 皮奥特

解决方法

WITH RECURSIVE
cte AS ( SELECT Id,Name,id BelongsToOrgId,Name UpperName
         FROM Organizations 
       UNION ALL
         SELECT Organizations.Id,Organizations.Name,cte.BelongsToOrgId,cte.Name
         FROM Organizations 
         JOIN cte ON Organizations.ParentId = cte.Id )
SELECT Id,BelongsToOrgId,CONCAT(Name,' is part of ',UpperName) Relation
FROM cte
ORDER BY Id,BelongsToOrgId;

fiddle

,

感谢Akina,

我们快到了,一个解决方法:

WITH RECURSIVE
cte AS ( SELECT Id,cte.UpperName
         FROM Organizations 
         JOIN cte ON Organizations.ParentId = cte.Id )
SELECT Id,BelongsToOrgId;

第5行是cte.UpperName,而不是cte.Name