使用MySQL查找树中的层数数量

3

我的行有相关的行,这些行可以有相关的行。这个树可以向下延伸多个级别(未知)。如何根据一个参数找到我的树有多少级别?

例如:

select * from category a 
inner join category b on a.row=b.relatedRow 
inner join category c on b.row=c.relatedRow where a.row=?

如果a中有项目,则为一级。如果b中有项目,则为二级,以此类推。这样我就能找到如果row=1,则存在与之相关的其他项目的三个层级。


使用一个扁平树例如闭包表:| ancestorRow | descendantRow | depth |。 查询语句:select max(depth) from category where ancestorRow = ? - Rocki
1个回答

0
创建两个PHP函数,一个用于获取主要类别,另一个用于获取主要类别的子类别。
function GetCategory($Cat_Id, $Cat_Name="")
{
$level = "";
echo $sql = "SELECT * FROM category WHERE 1=1 AND Cat_ParentId='0'";
$result = @mysql_query($sql);
while($row = @mysql_fetch_assoc($result))
{
    if(!empty($Cat_Id))
    {
        if($row['Cat_Id']==$Cat_Id)
        {
            $selected = "selected='selected'";
        }
        else
        {
            $selected = "";
        }
    }
    else
    {
        $selected="";
    }

    $resul .=  $level.$row['Cat_Name']."<br />";
    $resul .= GetSubCateogry($row['Cat_Id'], $level);
}
return $resul;
}
function GetSubCateogry($Cat_Id, $level)
{
$level .= "--";

$sql = "SELECT * FROM category WHERE Cat_ParentId = '$Cat_Id'";
$result = @mysql_query($sql);
while($row = @mysql_fetch_assoc($result))
{
    if(!empty($Cat_Id))
    {
        if($row['Cat_Id']==$Cat_Id)
        {
            $selected = "selected='selected'";
        }
        else
        {
            $selected = "";
        }
    }
    else
    {
        $selected="";
    }

    $resul .=  $level.$row['Cat_Name']."<br />";
    $resul .= GetSubCateogry($row['Cat_Id'], $level);
}
return $resul;
}
echo GetCategory(1);

你可以在查询中为特定子类别添加计数。 - Prateik Darji

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接