小编典典

MySQL + PHP的检索叶的孩子与路径

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

请帮我。


阅读 270

收藏
2021-04-28

共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();
2021-04-28