I have a table like
create table site
(
site_Id int(5),
parent_Id int(5),
site_desc varchar2(100)
);
Significance of the fields:
- site_Id : Id of the sites
- parent_Id : Parent id of the site
- site_desc : though not relevant to the question but it has the description of the site
The requirement is that if I have a site_id as an input, and I need all the ids tagged below the site. For Example:
A
/ \
B C
/ | \ /\
D E F G H
/\
I J
All the nodes are the site_Id.
The table contains data like this:
Site_id | Parent_ID | site_desc
_________|____________|___________
A | -1 |
B | A |
C | A |
D | B |
E | B |
F | B |
I | D |
J | D |
......
A is the parent of B and C and so on.
If B is the input given then the query need to fetch D, E, I, F, J
It is currently achieved through multiple queries in a loop, but I was thinking to achieve this in a minimum number of queries.
What I am currently doing is::
down vote
The algorithm goes like this :
Initially create a data set object which you will populate, by fetching data from the data base.
Create a method which takes the parent id as parameter and returns its child nodes if present, and returns -1, if it doesnt have a child.
Step1: Fetch all the rows, which doesn't have a parent(root) node.
Step2: Iterate through this result. For example if prod1 and prod2 are the initial returned nodes, in the resultset.
Iterating this RS we get prod1, and we insert a row in our DataSET obj.
Then we send the id of prod1 to getCHILD method, to get its child, and then again we iterate the returned resultset, and again call the getCHILD method, till we dont get the lowest node.
I need the best optimized technique within my data model constraint. Feel free to answer if you have any suggestion.
Please suggest anything.
Thanks in advance.