【问题标题】:How can I make this parent-child relationship work?我怎样才能使这种亲子关系发挥作用?
【发布时间】:2012-10-27 04:17:07
【问题描述】:

使用 MySQL 如何使这种层次结构起作用?

  • Parent 的 ID 为 100。此 Parent 的 ParentID 为 0。
  • 孩子的 ID 为 101。ParentID 为 100。
  • SubEntity 的 ID 为 105。ParentID 为 100。
  • 子实体的子实体的 ID 为 106。其 ParentID 为 105。

此查询将插入 iReport。目前,子实体及其子实体不会卷入父实体。

这就是我最终的结果:

`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`

【问题讨论】:

  • 澄清一下,您在 Parent 中有一条与另一行的 Parent ID 相关的记录?
  • 如果您能告诉我们您已经尝试过什么,将会很有帮助。
  • @YYY 为了尝试回答您的两个问题,数据不在基金表中。母基金有子基金和子基金,子基金也有子基金。现在,报告的工作原理是父母的孩子卷起。然而,子基金及其子基金只累积到子基金,他们也需要累积到父基金。现在,我正在将所有资金从表中提取出来,仅使用 where 子句中的基本标准
  • @Darvex 见上文,不知道你不能回复两个人,也感谢 Nikola K 编辑我的问题。
  • @nEWbie 但是您是否尝试在同一个表中跟踪这些关系?例如,它们都在同一个 Fund 表中,并且从那里开始有任何关系?

标签: mysql parent-child ireport


【解决方案1】:

是否有一个静态数字来控制这种父子关系的级别?

是的:使用递归LEFT JOINs X 次。

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

否:使用单独的查询来完成此操作,直到您根据需要充实您的父/子对象。确保您有适当的检查以避免循环,即。孩子是其父母的父母。

【讨论】:

    【解决方案2】:

    对于这种情况,您可以使用递归 CTE。看看这个链接,它给出了一个很好的例子。

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

    【讨论】:

    • 我的错,我没有看到 mySQL - 抱歉!
    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2011-02-04
    • 2014-06-22
    相关资源
    最近更新 更多