mysql + php检索带路径的叶子

时间:2011-04-19 18:29:34

标签: php mysql sql

我有一张像这样的桌子。

+-----------+-----------+-----------+-----------+-----------+-----------+
|id         | parent_id | name      | order     | status    | date_add  |
+-----------+-----------+-----------+-----------+-----------+-----------+
|1          | 0         | shoes     | 1         | 1         | 2011-04-02|
+-----------+-----------+-----------+-----------+-----------+-----------+
|2          | 1         | male      | 2         | 1         | 2011-04-02|
+-----------+-----------+-----------+-----------+-----------+-----------+
|3          | 1         | female    | 3         | 1         | 2011-04-02|
+-----------+-----------+-----------+-----------+-----------+-----------+
|4          | 3         | red shoes | 4         | 1         | 2011-04-02|
+-----------+-----------+-----------+-----------+-----------+-----------+

我想只选择叶子,以及它们的路径。

我想按如下方式得出结果:

+------+-------------------------------------+
| 2    | shoes/male                          |
+------+-------------------------------------+
| 4    | shoes/female/red shoes              |
+------+-------------------------------------+

如果这不仅sql也可以是php + sql

请帮帮我。

2 个答案:

答案 0 :(得分:1)

使用PHP打印出所有最后一个子节点的id和路径的非常简单的解决方案,因为我不知道在MySQL中这样做的方法。希望这有帮助!

function getChildren($parent= "", $x = 0) {
   $sql = "SELECT id, name FROM recurr WHERE parentId = $x";
   $rs = mysql_query($sql);
   //echo "Name: $parent has ". mysql_num_rows($rs)." children<br/>";
   while ($obj = mysql_fetch_object($rs)) {
      if (hasChildren($obj->id)) {
         getChildren($parent."/".$obj->name, $obj->id);
      } else {
         echo $obj->id .", ".$parent."/".$obj->name."<br/>";
      }
   }
}

function hasChildren($x) {
   $sql = "SELECT * FROM recurr WHERE parentId = $x";
   $rs = mysql_query($sql);
   if (mysql_num_rows($rs) > 0) {
      return true;
   } else {
      return false;
   }
}

只需拨打电话:

getChildren();

答案 1 :(得分:1)

我强烈建议为分层MySQL数据实现嵌套集模型。以下是更多信息的链接:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/。在链接中,您还可以找到问题的答案(在“邻接列表模型”,“查找所有叶子节点”部分下)