简体   繁体   中英

How can I make this parent-child relationship work?

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 JOIN s X times.

SELECT *
FROM table t1 LEFT JOIN table t2
  ON t1.id = t2.parent_id
  LEFT JOIN table t3
  ON t2.id = t3.parent_id
  ...

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.

You could use a Recursive CTE for this scenario. Take a look at this link, it gives a good example.

http://blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM