MySQL返回每个父级及其子级的列表

时间:2017-12-03 07:57:00

标签: mysql sql plsql mysql-workbench recursive-query

我有一张如下表:

经理是父母,并且拥有加入经理父母身份的子资源。

id    | parent_id   |   Role       | Number of roles

123   | 123         | Manager      |    2

124   | 123         | Resource     |    1

125   | 123         | Resource     |    2

128   | 128         | Manager      |    1

126   | 128         | Resource     |    4

127   | 128         | Resource     |    3

我的sql查询应为每个父级返回以下结果:

id    | parent_id   |   Role       | Sum of manager only | Total resources

123   | 123         | Manager      |    2                |    2+1+2 = 5 (Manager + the total number of resources for parent id 123)   

128   | 128         | Manager      |    1                |    1+4+3 = 8 (Manager + the total number of resources for parent id 128)   

任何帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:0)

我希望这样做:

scanf("%c",&s[i].gender);

答案 1 :(得分:0)

您只需要使用父ID进行自我加入。如果你的表名是“tbl_manager”

SELECT t1.id,
    SUM(IF(t1.id = t2.id, 1,0)) AS is_manager,
    t1.parent_id, 
    t1.Role, 
    t1.Number_of_Role AS Sum_of_manager_only,
    IFNULL(SUM(t2.Number_of_Role),0) AS Total_resources 
FROM  tbl_manager AS t1 
LEFT JOIN  tbl_manager AS t2 
    ON t2.parent_id = t1.id 
GROUP BY t1.id
HAVING is_manager;

答案 2 :(得分:-1)

您可以使用子查询

select
    (select id from mytbl where id=r.parent_id)  id
    ,r.parent_id
    ,(select sum(NofRole) from mytbl where parent_id=r.parent_id and Role='Manager') [Sum of manager only]
    , sum(r.nofrole) [Total resources]
    from mytbl r
    group by r.parent_id