-1

I have a table like this :

id    title      parent_id
1       A           0
2       B           0
3       C           1
4       F           3
5       O           3
6       D           2
7       J           6
8       T           2
9       P           8


A
   C
      F
      O

B
  D
    J
  T
    P

now, if I give 2, this function should return:

6
8
7
9

and also if I give 3 it function should return:

4
5 
  • I don't want just leaf nodes !!!
  • I think there is a sql query.
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • 1
    There is similar question and good answer here: http://stackoverflow.com/questions/2915748/convert-a-series-of-parent-child-relationships-into-a-hierarchical-tree . This might be a duplicate question then. – Nikola Kirincic Nov 17 '16 at 08:31

2 Answers2

0

I think you need to join table with itself. I haven't try it myself but it is like code below

SELECT a.id, a.title 
FROM tbl AS a 
WHERE a.id = :id

UNION

SELECT b.id, b.title
FROM tbl AS a
INNER JOIN tbl AS b ON a.id = b.parent_id 
WHERE a.id = :id

UNION

SELECT c.id, c.title
FROM tbl AS a
INNER JOIN tbl AS b ON a.id = b.parent_id
INNER JOIN tbl AS c ON b.id = c.parent_id 
WHERE a.id = :id

UNION

SELECT d.id, d.title
FROM tbl AS a
INNER JOIN tbl AS b ON a.id = b.parent_id
INNER JOIN tbl AS c ON b.id = c.parent_id 
INNER JOIN tbl AS d ON c.id = d.parent_id 
WHERE a.id = :id

 ...

Keep adding query until number of depth you require. There is other approach for example using stored procedure.

Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40
0

just sql :

select  id,
        title,
        parent_id 
from    (select * from products
         order by parent_id, id) base,
        (select @pv := '3') tmp
where   find_in_set(parent_id, @pv) > 0
and     @pv := concat(@pv, ',', id)
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254