I got to develop a user chain as shown in the figure. At level zero it has one member, level one two, level two will have 4, level 3 has 8 members..like wise 9th level will have 512 members and it is final stage.
In the programmatic view, to interrelate a member's position with his right & left wing to a level of x
, running 2^x
queries is pathetic. (for 9th level, 2^9 queries will hit db)
Is there any other way to reduce no of hits to db? How can we better map the relation between the members?
An excellent titorial for Storing Hierarchical Data in a Database .
Also, HERE is a similar question, with a few solid solutions.
construct a tree table and zone table. Tree table will contain parent, child, side as columns. Zone table contains userid, zone (into which all zones it should be displayed, 9 in this case) and length (length from the top most parent node) as columns. so in zone table 1st level node will have one entry, 2nd row node will get two entry, similarly 9th will have nine entries.
Now when a node has to be displayed, to retrieve all its below nodes, write a query like select * from zone where userid=xx
now map this result with tree table to decide which node comes under which node and which side.
Get all the data from your db in the form of Parent-Child relation and then store the result set in Binary Tree
Parent Child
=====================
NULL 17265
17265 17270
17265 17394
17270 17796
17270 17797
...
...
...
...
Now using this it becomes easy to plot your Binary Tree (infact any Tree)
So your function prototype to add nodes will look something like this
public void add(int parent, int child);
NOTE:
The method prototype is of Java Language .
in a relational database I would create one single table like
create table node(
nodeid bigint not null primary key,
nodeparent bigint references node ( nodeid ),
nodegroup bigint,
nodename varchar( 80 ), // add attributes as needed
);
Do a query like "SELECT * FROM node WHERE nodegroup = 17 ORDER BY nodeid" to obtain all nodes in one result set. Scan through the set and create the tree in memory.
Hajo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.