如何在SQL CTE中的MLM二叉树中对下线中的用户的总左和右子进行计数

时间:2014-11-11 09:52:44

标签: sql-server tsql hierarchical-data recursive-query

我从父子关系中获得以下结果时遇到一些问题,请检查以下表格结构 enter image description here

以上是表结构,树结构如下图所示。 enter image description here

如果我的情况在这里是一个MLM树,其中每个人在左侧和右侧都有下线成员。所以我需要在他们的下线为当前登录用户计算

所以我需要提前感谢提前获得正确的摘要

    ALTER Function [dbo].[F_SearchUsersTreeByParent](@id as int)
Returns table as 
Return


WITH CTE_Table (id, FullName,UserName, RefferdByID,Levels,LevelPrice, IsPurchasedProduct)
AS
(
SELECT id, FullName,UserName,-1 as RefferdByID,Levels,LevelPrice,IsPurchasedProduct
FROM Registration WHERE id = @id and Registration.IsPurchasedProduct=1
UNION ALL
SELECT Registration.id, Registration.FullName,Registration.UserName, Registration.RefferdByID,Registration.Levels,Registration.LevelPrice, Registration.IsPurchasedProduct FROM Registration
JOIN CTE_Table ON Registration.RefferdByID = CTE_Table.id
where Registration.IsPurchasedProduct=1
)

SELECT id, FullName,UserName, RefferdByID,Levels,LevelPrice, IsPurchasedProduct,

(Select count(*)-1 from dbo.F_CountRefered(id) where id<>abc.id) as RefCount
 FROM CTE_Table as abc

1 个答案:

答案 0 :(得分:0)

$memid="95000";   // your id

function getTotalLeg($memid,$leg){ 
      global $conn;
     $sql="select child_class from tree_class where parent_id='".$memid."' and position='".$leg."'";
      $res=mysqli_query($conn,$sql);
      $row=mysqli_fetch_array($res);
      global $total;
       $total=$total+mysqli_num_rows($res);
         if($row['child_class']!=''){
           getTotalLeg ($row['child_class'],'L');
           getTotalLeg ($row['child_class'],'R');
          } 
          return $total;      
        }      

     $total=0; 
    $left=getTotalLeg($memid,"L");    
    echo $total."</br>"; 
     $total=0;
    $right=getTotalLeg($memid,"R");  
    echo $total;