Search code examples
mysqlhierarchyhierarchical-datarecursive-query

MySQL Recursive get all child from parent


i have this case using recursive query on Mysql to find lv 2 and lv3 child on one table...
database structure i'm using:

id name parent
1    A    0
2    B    0
3    C    0
4    D    1
5    E    1
6    F    2
7    G    2
8    H    3
9    I    3
10   J    4
11   K    4

The result i was expecting, when filtering the data, where id=1, it will generate the result i'm expecting.

id name parent
4   D     1
5   E     1
10  J     4
11  K     4

or this is the illustration. Illustration

i've been looking everywhere, and reading this http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, but i didn't find the result i was looking for..
any help would be appreciated, thanks


Solution

  • SELECT *
    FROM TABLENAME
    WHERE PARENT = 1
    UNION
    SELECT * 
    FROM TABLENAME
    WHERE PARENT IN 
        (SELECT ID FROM TABLENAME WHERE PARENT = 1)