I have a table where I store information of directories (like in a filesystem). Each directory (named node) has a nodeid
and a parentid
. I want to retrieve a full path as efficiently as possible. For this, I am trying to make the following queries work, but these return just the first expected row (that is in fact the inner most directory). Can anyone help to get the full result set so that all hierarchical parents of given directory/node are also selected.
The Queries I am currently experimenting with:
SET @var:= 8;
SELECT * , @var:=parentid FROM `app_nodes` WHERE nodeid IN ( @var )
Alternative:
SET @var:= 8;
SELECT * , @var:=parentid FROM `app_nodes` WHERE nodeid=@var
Alternative:
SET @var:= 8;
SELECT * FROM `app_nodes` WHERE nodeid=@var AND (@var:=parentid)
#the parentid of the first parent is '0', so I expect it to end there.
Sample data:
nodeid parentid
1 0
2 0
3 0
4 0
5 3
6 5
7 0
8 6
9 0
10 0
11 5
12 6
13 11
14 11
Desired output:
nodeid parentid
3 0
5 3
6 5
8 6
Can anyone please help?