I'm working with an SQL Server database and I have the following two tables:
Nested Apps Nested App Groups
|---------------------|------------------| |---------------------|------------------|
| App_Group | App | | App_Group | Child_App_Group |
|---------------------|------------------| |---------------------|------------------|
| 5 | A | | 1 | 4 |
|---------------------|------------------| |---------------------|------------------|
| 7 | B | | 4 | 5 |
|---------------------|------------------| |---------------------|------------------|
| 9 | C | | 2 | 6 |
|---------------------|------------------| |---------------------|------------------|
| 6 | 7 |
|---------------------|------------------|
| 3 | 8 |
|---------------------|------------------|
| 8 | 9 |
|---------------------|------------------|
On the left we can see the parent/child relation between App Groups and Apps. On the right we can see the parent/child relation between App Groups and Apps Groups (Apps can not have children). In the example App A is a child of App Group 5, which is a child of App Group 4, which then is a child of App Group 1.
I want a table that shows the nested parent/child relation of App Groups and Apps, regardless of whether the App is a direct child or a "grandchild", etc... Like this:
|---------------------|------------------|
| App_Group | App |
|---------------------|------------------|
| 1 | A |
|---------------------|------------------|
| 4 | A |
|---------------------|------------------|
| 5 | A |
|---------------------|------------------|
| 2 | B |
|---------------------|------------------|
| 6 | B |
|---------------------|------------------|
| 7 | B |
|---------------------|------------------|
| 3 | C |
|---------------------|------------------|
| 8 | C |
|---------------------|------------------|
| 9 | C |
|---------------------|------------------|
I've not really come close to solving it. I've tried to work with the idea that I somehow have to run through the hierarchy which would be a bit easier if I had one App at a time. But here I have to do it with three Apps at once. I have no idea how to even begin... Anyone?
UPDATE:
I've come very close with something like this:
WITH cte AS ( SELECT app_group_id, app_id FROM nested_apps UNION ALL SELECT
nag.app_group_id, c.app_id FROM nested_app_groups nag JOIN cte c ON
nag.child_app_group_id = c.app_group_id ) SELECT app_group_id, app_id FROM
cte