获取给定叶子ID的根节点

时间:2014-09-10 11:07:33

标签: mysql sql select

我收到了以下表格:

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

这是一个树中的结果,类似于PRODUCT_BUNDLES表中某些产品的ID之间的关系:

        p1
       /   \
      p2   p3
          / | \
        p4  p5 p6

用户给我下面的id p2,p4,p5和p6(树的叶子),我想要返回p1 id(树的根)。

我如何在mysql中构建select查询来做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以像this one

一样创建PROCEDURE
 CREATE PROCEDURE get_root(IN id int)
  BEGIN
  DECLARE child_id int;
  DECLARE prev_id int;
  SET prev_id = id;
  SET child_id= -1 ;
  SELECT parent_product_id into child_id 
  FROM PRODUCT_BUNDLES WHERE child_product_id= prev_id ;
  WHILE child_id <> -1 DO
    SET prev_id = child_id;
    SET child_id= -1 ;
    SELECT parent_product_id into child_id 
    FROM PRODUCT_BUNDLES WHERE child_product_id = prev_id ;
  END WHILE;
  SELECT child_id ;
  END