dongzi4030 2015-07-21 11:50
浏览 7

层次结构/树数据 - 查找原点

Imagine a tree. I would like to trace back to the trunk of the tree given any branch on that tree, with the number of branches within branches being unlimited. There are no many-to-many connections.

I am logging customers and have set up a table to show which existing customer recommended a new customer to us, so this has spread out to somewhat of a "family tree".

Every time a new customer comes on board, I need to know the original customer at the origin of the tree that started everything.

Here is a mock-up of my table to show 2 "families", with 1 and 11 being the top of the tree for each. Each parent has 2 children in this example and each number is a foreign key for a customer's contract number.

parents children
1       2
1       3
2       4
2       5
3       6
3       7
11      12
11      13
12      14
12      15
13      16
13      17

So far, I have been using MySQL and a PHP loop to SELECT a parent WHERE the child has a specific contract number, then looking to see if that parent is a child itself in the same table. I keep this loop going until no rows are returned and I get the answer.

My question is, is this the most efficient way to do this, or is there a solution outside of PHP, or by redesigning the table? I can see there being hundreds of "generations" soon and I don't want it to start getting too slow.

  • 写回答

2条回答 默认 最新

  • dongsui0929 2015-07-21 12:18
    关注

    What you're looking for is the Nested set model. It allows to store hierarchical data in a relational database.

    Have a look at this answer, it will give you the idea of how to find the origin of any record.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错