[英]Database Schema Design Suggestion Required?
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. 这里的User1_1是User1的子用户,而User1_2_2是User1_2的子用户。 it is the problem of self reference table but in 3 to 4 level deep.
这是自参考表的问题,但深度为3到4级。 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..
请告诉我最好的方法,谢谢..
If there is only ever, either 0 or 1 parents to a user why not use the following structure 如果只有一个,则用户的父母为0或1,为什么不使用以下结构
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 :)) 要获得树状结构,可以使用递归CTE,如果您希望我发布此额外信息,请随时发表评论(但请先尝试:)
Good Luck! 祝好运!
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) 它应该返回1(User1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.