MySQL Hierarchy – Getting Root Node for Given Leaf IDs

hierarchyMySQL

I got the following tables:

  +-----------------+
  | PRODUCTS        |
  +-----------------+
  | #product_id     |
  | #company_id     |
  +-----------------+
        |     |
+---------------------+
| PRODUCT_BUNDLES     |
+---------------------+
| #parent_product_id  |
| #child_product_id   |
| #company_id         |
+---------------------+

And here is a result in a tree like of the relationships among ids in the PRODUCT_BUNDLES table for some product:

        p1
       /   \
      p2   p3
          / | \
        p4  p5 p6

A user give me the following ids p2, p4, p5 and p6 (the leafs of the tree) and I want return the p1 id (the root of the tree).

How I build select query in mysql to do that?

For now I only have the inverse query. From a root ID give the descendent's IDs.

SELECT bundles.product_id FROM products_bundles bom INNER JOIN products products ON products.product_id = bom.parent_product_id INNER JOIN products bundles ON bundles.product_id = bom.child_product_id WHERE products.product_id = SOMEID;

To clarify what I search is a query that return the parent who have all product_id given as descendant not the parent who have some product_id given as descendant. Thanks

Best Answer

A long, long time ago (Oct 24, 2011), in a galaxy far away, someone boldly asked

Find highest level of a hierarchical field: with vs without CTEs

In my answer to that post, I wrote three stored procedures to find specific relationships

  • GetParentIDByID
  • GetAncestry
  • GetFamilyTree

If you use the code in GetAncestry, just pick the last Ancestor in the output.

I have referred others to that post

In your particular case, you would run GetAncestry on each node and compile it into a distinct list. If the nodes all belong to one tree, you should get one node (in your case, p1). If the nodes are from different trees (from a forest), your compiled list will have multiple root nodes.

Give it a Try !!!