2013-03-13 137 views
-3

我有两张桌子。 组(Id,title,parentGroupID) 帐户(AID,GroupID,标题,Balanace)。母公司总数

ID | Title | parentGroupID 
1 | Assets| 0 
2 | Bank | 1 
3 | myBank| 2 
4 | cash | 1 

账户

AID | GroupID | Title  | Balanace 
1 | 3  | acc1234  | 5000 
2 | 3  | acc002  | 10000 
3 | 4  | counter cash | 60000 

现在我想表明资产= 5000 + 10000 + 60000所有的资产组的成员。

+3

欢迎StackOverflow上。请从[FAQ](http://stackoverflow.com/faq)寻求指导。请用[你试过的]更新你的答案(http://www.whathaveyoutried.com)。 – Kermit 2013-03-13 15:25:59

+0

是否有数量有限的组? (在示例数据中显示最多有三个级别 - myBank属于Bank,属于Assets。) – 2013-03-13 15:28:36

+1

请参见[管理MySQL中的分层数据](http://mikehillyer.com/articles/managing-hierarchical-data -in-mysql /) – Barmar 2013-03-13 15:30:16

回答

0

玩这个,看看你会得到什么:

SELECT 
    t1.Title as Group1, 
    t2.Title as Group2, 
    t3.Title as Group3, 
    t4.Title as Group4, 
    t5.Title as Group5, 
    a1.Title as SubGroup1, 
    a2.Title as SubGroup2, 
    a3.Title as SubGroup3, 
    a4.Title as SubGroup4, 
    a5.Title as SubGroup5, 
    t1.parentGroupID, 
    t2.parentGroupID, 
    t3.parentGroupID, 
    t4.parentGroupID, 
    t5.parentGroupID, 
    a1.Balance, 
    a2.Balance, 
    a3.Balance, 
    a4.Balance, 
    a5.Balance 
      FROM GROUPS t1 
     LEFT JOIN GROUPS t2 ON t2.parentGroupID = t1.ID 
     LEFT JOIN GROUPS t3 ON t3.parentGroupID = t2.ID 
     LEFT JOIN GROUPS t4 ON t4.parentGroupID = t3.ID 
     LEFT JOIN GROUPS t5 ON t5.parentGroupID = t4.ID 
     LEFT OUTER JOIN ACCOUNTS a1 ON a1.GroupID = t1.ID 
     LEFT OUTER JOIN ACCOUNTS a2 ON a2.GroupID = t2.ID 
     LEFT OUTER JOIN ACCOUNTS a3 ON a3.GroupID = t3.ID 
     LEFT OUTER JOIN ACCOUNTS a4 ON a4.GroupID = t4.ID 
     LEFT OUTER JOIN ACCOUNTS a5 on a5.GroupID = t5.ID 
WHERE t1.parentGroupID = 0 
+0

显示结果为group1,group2,group3,subgroup1 ... balance,balnce,blance 我想要的是 groupID,GroupTtitle,balanace 1资产210000 – user2166048 2013-03-13 20:46:43