我一直在获取父 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
谢谢大家的回复,但从当前的情况来看,我分析由于版本问题,MY SQL 无法解决这个问题,因为最终这个递归查询在某个时候中断。
所以我必须在 PHP 中使用相同的查询创建一个递归函数,该查询在 Child 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;
}
}
您正在使用一种脆弱的方式来模拟递归查询。它特别要求父行必须在子行之前排序。
基本行集正在使用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 的版本,因为只要您不想更改数据模型,每种解决方法都会有一些限制(例如行顺序或最大深度(。
旁注:MySQL可以忽略子查询(特别是testdata_sorted
(中的order by
,您可能需要验证它是否不需要(这可能取决于版本,索引或表大小等因素(。