php mysql query query :D
This question has two parts. An answer to either part would be great :D
1) I am using one table to store links between values of another table. I am then searching through that table to find inheritance lists.
while($cont) {
$rst = DB::query("SELECT parentID FROM code_inheritance WHERE childID=".$sid);
if($rst->num_rows != 0) {
$ob = $rst->fetch_object();
if($list != '') $list .= ',';
$list .= $ob->parentID;
$sid = $ob->parentID;
} else $cont = false;
}
DB is my database class. However, this isn't a very efficient way of searching a database. Can anyone point me in a direction where I can do this in one database query please?
2) I then use the list to search for the names of the classes so that I can echo an inheritance list to the screen, however they are returned in ID numerical order I want them to be in the order they were found in part 1. I am currently doing this:
if($list != '') {
$rst = DB::query("SELECT Name FROM code WHERE ID IN ($list)");
$list = '';
while($ob = $rst->fetch开发者_开发技巧_object()) {
echo $ob->Name;
if($list != '') $list .= ' -> ';
$list .= '<a href="/code/'.$ob->Name.'/">'.$ob->Name.'</a>';
}
$list = "Inheritance -> ".$list;
}
How can I get then list in the order I found them in part one so that the inheritance tree is in the correct order?
Sorry that this was a bit lengthy but I wanted to add as much information as I could.
A Sub-Query could be helpful so aviod the first part:
SELECT Name FROM code WHERE ID IN
(SELECT parentID FROM code_inheritance WHERE childID='$sid')
This selects all your parentID
in the inner query and then use this to find the code.name
. Using IN
might not return the correct order as it is just a set which has no particular order. So you should add some "orderable" column.
To get all IDs within one query as list you can use GROUP_CONCAT
, more information at MySQL manual about group by
.
精彩评论