Question

I have a user Table.. A user can have many sub user .. and each sub user may have a number of sub user.

User Table.
Id      UserName   other...No of columns.
 1      User1
 2      user2
 3      user1_1
 4      user1_2
 5      user1_2_1
 6      user1_2_2

here User1_1 is the sub user of User1 and User1_2_2 is the sub user of User1_2. it is the problem of self reference table but in 3 to 4 level deep. i want to who is the master of a specific user or grand master ?

group Table.
Id  ,   Owner_userId
1   ,     1
2   ,     4


user_groupTable
 groupId , UserId
   1     ,  3
   1     ,  4
   2     ,  5
   2     ,  6

through this I can achieve my target. I am wandering is there best approach to solve this problem ? the difficultly with this approach queries may get complex. please tell me a best approach, and thanks..

Was it helpful?

Solution 2

You could do it like this:

CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
parent_id int(11) NOT NULL DEFAULT '0',
user_name varchar(32),
.... more columns ...
);

and insert some data here:

INSERT INTO users VALUES (1,0,'User1');
INSERT INTO users VALUES (2,0,'User2');
INSERT INTO users VALUES (3,1,'User1_1');
INSERT INTO users VALUES (4,1,'User1_2');
INSERT INTO users VALUES (5,4,'User1_2_1');...

And create a function like:

CREATE FUNCTION f_get_top_user_id (xusers_id INT)
RETURNS text
DETERMINISTIC
BEGIN

DECLARE xtop_id int;
DECLARE xparent_id int;

SELECT u.parent_id INTO xparent_id FROM users u WHERE u.id = xusers_id;
SELECT u.id INTO xtop_id FROM users u WHERE u.id = xusers_id;

WHILE (xparent_id > 0) DO
    BEGIN
        SELECT u.id INTO xtop_id FROM users u WHERE u.id = xparent_id;
        SELECT u.parent_id INTO xparent_id FROM users u WHERE u.id = xparent_id;
    END;
END WHILE;

RETURN xtop_id;

END

And if you call that function like

SELECT f_get_top_user_id(5);

it should return 1 (User1)

OTHER TIPS

If there is only ever, either 0 or 1 parents to a user why not use the following structure

User Table.
Id      UserName   other...No of columns. ParentUserID
 1      User1                             NULL
 2      user2                             NULL
 3      user1_1                           1
 4      user1_2                           1
 5      user1_2_1                         4
 6      user1_2_2                         4
 7      user2_1                           2

This is a really simple approach from this you will be able to get all the top level (grand master) users with

SELECT * FROM dbo.Users WHERE ParentID = NULL

To Get A Specific user's parent you will be able to do

SELECT * FROM dbo.Users WHERE ID = *then what ever the parent user ID of the user you are looking at*

To get a tree structure you can use Recursive CTEs feel free to comment if you want me to post this extra info (but try it yourself first :))

Good Luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top