Using MySQL how can I make this hierarchy work?
- Parent’s ID is 100. This Parent has a ParentID of 0.
- Child has an ID of 101. The ParentID is 100.
- SubEntity has an ID of 105. The ParentID is 100.
- Child of Subentity has an ID of 106. Their ParentID is 105.
This query will be plugged into iReport. Currently the Subentity and it’s children do not roll up into the Parent.
This is what I ended up going with:
`Select
case
when FC.ParentType = 'PARENT' then FC.FundCode
when FB.ParentType = 'PARENT' then FB.FundCode
when F.ParentType = 'PARENT' then F.FundCode
else 0 end as `ParentID`,
case
when FB.ParentType = 'SUBFUND' then FB.FundCode
when F.ParentType = 'SUBFUND' then F.FundCode
else 0 end as `SubfundID`,
case
when FB.ParentType = 'CHILD' then FB.FundCode
when F.ParentType = 'CHILD' then F.FundCode
else 0 end as `Children`,
F.FundName
From Fund F
join Fund FB on F.ParentId = FB.FundCode
join Fund FC on FB.ParentID = FC.FundCode`
Is there a static number governing how many levels this parent-child relationship has?
Yes: Use recursive
LEFT JOINs X times.No: Accomplish this using separate queries until you have fleshed out your Parent/Child objects as far as you want. Make sure you have checks in place to avoid loops, ie. a child is a parent of its parent.