0

My Tree Structure isenter image description here

and the database table i have created is enter image description here

how create select query to get all the child node of any particular node in tree structure db table.

for Example i pass superior_emp_id=1 then it return {2, 3, 4, 5, 6, 7}

java baba
  • 2,199
  • 13
  • 33
  • 45

4 Answers4

0
select * 
from employee 
where superior_emp_id = @emp_id  

union all  

select * 
from employee 
where superior_emp_id in (select emp_id 
                          from employee 
                          where superior_emp_id = @emp_id)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
juds
  • 69
  • 1
  • 2
0

Well you can make use of nested queries and sets here,

You can try the following query for getting the child nodes of root node:

select *
from TABLE_NAME
where senior_emp_id in { select emp_id
                         from TABLE_NAME
                         where senior_emp_id = 1 || emp_id = 1 }

Similarly if you put 2 in place of 1 in the nested query if you want to have child nodes of Parent node -2

Let me know if it's working well ..

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Khay
  • 981
  • 1
  • 10
  • 22
0
StringBuilder sql = new StringBuilder();
        sql.append("SELECT emp_id AS id, ");
        sql.append("  emp_name AS employeeName, ");
        sql.append("  title AS title, ");
        sql.append("  superior_emp_id AS parentId ");
        sql.append(" FROM T_NWM_SRVC ");
        sql.append(" WHERE superior_emp_id IS NOT NULL ");
        sql.append(" AND superior_emp_id  =");
        sql.append(parentId);

On passing parentId : 1 you will retrieve 2,3.For getting childnodes of 2,3 you will have to do a server call again(Kind of lazy loading). Hope this is what you are looking for.

Dev
  • 3,922
  • 3
  • 24
  • 44
0

I think that you cant do this with one sql Statement. I would try to implement a recursive function that querys for a set of given ids if there more childs and append them. Prosa:

function List<Integer> getChilds(int[] ids)
{  
List<Integer> returnValue = new ArrayList();
if(ids.length = 0)
    return returnValue;

foreach int id : ids
{
    //Build sql to get childs an execute it
    int[] childidsfromsql = em.createQuery("...").getResultList();..
    returnValue.addAll(getChilds(childidsfromsql))
}
 return returnValue;
}
Matthias H
  • 1,300
  • 13
  • 19
  • try using List only, and do not convert from int array to list xD i hope u can understand the idea behind this prosa code – Matthias H Dec 16 '13 at 07:58