【问题标题】:Find number of levels in a tree using MySQL使用 MySQL 查找树中的级别数
【发布时间】:2016-07-13 00:00:33
【问题描述】:

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

例如:

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 中有项目,则为1 级。如果b 中有项目,则为2 级,依此类推。这样我可以发现,如果row=1,有3个级别的其他项目是相关的。

【问题讨论】:

  • 使用扁平树,例如闭包表:| ancestorRow | descendantRow | depth | 。查询:select max(depth) from category where ancestorRow = ?

标签: php mysql pdo


【解决方案1】:

创建两个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);

【讨论】:

  • 您可以在查询中添加计数以获取特定的子类别计数
猜你喜欢
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多