繁体   English   中英

MYSQL-从父母那里得到所有孩子

[英]MYSQL - Get all children from the parents

我一直在获取所有孩子的查询,其中父母ID大于客户ID

表测试

  id    name    parent
    1   test1   0
    2   test2   1
    3   test3   1
    4   test4   2
    5   test5   2
    6   test6   10
    7   test7   10
    8   test8   6
    9   test9   6
    10  test10  5
    11  test10  7

目前,我正在使用此递归查询,但它显示直到10个父级的子级,但不能给出6个和7个子级的子级

SELECT id , parent FROM (SELECT  id , parent from (SELECT * FROM test order by
parent , id) testdata_sorted, (SELECT @pv := '1') initialisation where 
find_in_set(parent , @pv) > 0 and @pv := concat(@pv, ',', id)  ORDER BY 
parent ASC) AS tt

当前输出为->

id  parent
2   1
3   1
4   2
5   2
10  5
6   10
7   10

我需要这种类型的输出。 在这方面我需要帮助。

id  parent
2   1
3   1
4   2
5   2
10  5
6   10
7   10
8   6
9   6
11  7

您正在使用一种脆弱的方式来模拟递归查询。 它特别要求父行必须在子行之前排序

您的基本行集正在使用order by parent, id

id  parent
----------------------
1   0
2   1         -- fine
3   1         -- fine 
4   2         -- fine
5   2         -- fine 
10  5         -- fine 
8   6         -- parent 6 comes later!
9   6         -- parent 6 comes later! 
11  7         -- parent 7 comes later!
6   10        -- fine
7   10        -- fine

您会看到这些正是结果中缺少的行。

对此没有简单的解决方法,因为要动态排序行以便能够在递归查询中使用,您需要一个递归查询。 不过,您也许可以通过满足该条件的方式输入数据。 虽然我认为问题中父代ID大于客户ID的部分实际上不是条件(因为您的预期输出与此不符):如果您约束父子的条件,它可能会给您可能的命令。

有关建模数据或编写查询的替代方法,请参见如何创建MySQL分层递归查询 实际上,小工具答案中包含有关代码订购要求的说明。

最好使用支持递归CTE的版本,因为只要您不想更改数据模型,针对这些问题的每种解决方法都有一定的局限性(例如,行顺序或最大深度)。

附带说明:MySQL可以忽略子查询中的order by (特别是testdata_sorted ),您可能必须验证它是否不这样做(这可能取决于版本,索引或表大小)。

谢谢大家的答复,但是从当前情况来看,我分析由于版本问题,MY SQL无法解决此问题,因为最终此递归查询在某个时刻中断。

因此,我必须使用相同的查询在PHP中创建一个递归函数,该查询在“子代ID”大于“父代ID”处中断,并使用该中断ID一次又一次调用相同的函数,并在同一数组中添加数据。 这给出了我想要的结果。

function getallchilds($customer_parent_id){

$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$downlineChilds =array();
$breakbleIds =array();

    $getallchilds = $read->fetchAll("SELECT id , parent FROM (SELECT  id , parent from (SELECT * FROM test order by
parent , id) testdata_sorted, (SELECT @pv := '".$customer_parent_id."') initialisation where 
find_in_set(parent , @pv) > 0 and @pv := concat(@pv, ',', id)  ORDER BY 
parent ASC) AS tt");

    foreach($getallchilds as $childs) {
          $downlineChilds[] =  array($customer_parent_id => $childs['id']);
          if ($childs['parent'] > $childs['id']) {
            $breakbleIds[] =  $childs['id']; 
          }
        }

    $checkbreakIDS = count($breakbleIds);
    if($checkbreakIDS > 0 ){
        foreach($breakbleIds as $breakbleId) {
            $childrens = getallchilds($breakbleId);
            if ($childrens){
                $downlineChilds = array_merge($downlineChilds,$childrens);
            }
        }
        return $downlineChilds;
    }
    else{
        return $downlineChilds;
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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