mysql + php retrieve leaf children with path
I have a table that like this.
+-----------+-----------+-----------+-----------+-----------+-----------+
|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|
+-----------+-----------+-----------+-----------+-----------+-----------+
I want to select only the leaf children, with their path.
I want to come to the result as fol开发者_开发技巧lows:
+------+-------------------------------------+
| 2 | shoes/male |
+------+-------------------------------------+
| 4 | shoes/female/red shoes |
+------+-------------------------------------+
if this does not only sql can also be php + sql
Please help me.
Very simple solution to print out id and path to all last child nodes using PHP as I am not aware of a way of doing this within MySQL. Hope this helps!
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;
}
}
To run just call:
getChildren();
I highly recommend implementing nested set model for hierarchical MySQL data. Here is the link for more info: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/. In the link, you will also find the answer to your question (under "The Adjacency List Model", "Finding all the Leaf Nodes" section)
精彩评论