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

uhry853o  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(406)

我一直在获取父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
x759pob2

x759pob21#

感谢大家的回答,但从目前的情况来看,我分析,由于版本问题,我的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;
    }

}
fafcakar

fafcakar2#

您正在使用一种脆弱的方法来模拟递归查询。它特别要求父行必须在子行之前排序。
您的基本行集正在使用 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分层递归查询。实际上,trincots的答案中包含了一条关于代码的顺序要求的注解。
最好使用支持递归CTE的版本,因为只要您不想更改数据模型,每个解决方法都有一些限制(例如行顺序或最大深度)。
旁注: order by 在子查询中(特别是 testdata_sorted )可以被mysql忽略,您可能需要验证它是否没有被忽略(这取决于版本、索引或表大小)。

相关问题