I am very tired getting tree based result, which id on which position. But not reached, also saw many answer like select and select
Here is my table
CREATE TABLE `memberinfo` (
`id` int(11) NOT NULL auto_increment,
`parentid` int(11) NOT NULL default '0',
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
id parentid name
1 0 abc1
2 1 abc2
3 2 abc3
4 2 abc4
5 0 abc5
6 3 abc6
I want result position like:
id position
1 1
2 1-1
3 1-1-1
4 1-1-2
5 2
6 1-1-1-1
Thank you for help in advance.
I try in php recursive but it too slow and at last get fatal error(Excution time out)
function getPosition($listparentid,$listid){
$db = new dbfunction();
$posNumber = '';
do{
$listresult = $db->rootPostionSearch($listparentid,$listid);
$rowcount=mysqli_num_rows($listresult);
if($rowcount > '0'){
if ($listrow = mysqli_fetch_assoc($listresult)) {
//switch to parent id
$listid = $listrow['parentid'];
//get next parent id
$presult = $db->getRootParentInfo($listid);
$pcount=mysqli_num_rows($presult);
if($pcount > '0'){
if ($plistrow = mysqli_fetch_assoc($presult)) {
$listparentid = $plistrow['parentid'];
}
}
//get position
$posNumber = $listrow['position']."-".$posNumber;
}
}
}while($listparentid != '0');
// get parent position number
$listresult = $db->rootPostionSearch($listparentid,$listid);
$rowcount=mysqli_num_rows($listresult);
if($rowcount > '0'){
if ($listrow = mysqli_fetch_assoc($listresult)) {
//get position
$posNumber = $listrow['position']."-".$posNumber;
}
}
return $posNumber;
}
public function getRootParentInfo($id){
$sql = "select parentid from memberinfo where id = $id";
return $this->query($sql);
}
public function rootPostionSearch($rootpos,$pos){
$sql = "SELECT x.id, x.parentid, x.position, x.name
FROM
(
SELECT t.id, t.parentid, t.name,@rownum := @rownum + 1 AS position
FROM memberinfo t
JOIN (SELECT @rownum := 0) r
where t.parentid = '$rootpos' order by id
) x where id = '$pos'";
return $this->query($sql);
}
Level query :
SELECT x.id, x.parentid, x.position, x.name
FROM
(
SELECT t.id, t.parentid, t.name,@rownum := @rownum + 1 AS position
FROM memberinfo t
JOIN (SELECT @rownum := 0) r
where t.parentid = '0' order by id
) x