我们正在与MLM项目合作。这个项目的基本思路就像
我的SQL Server表结构类似于
user_details
https://i.stack.imgur.com/xcHGd.jpg
现在理论上
A's Team Members are => B , C , D
B's Team Members are => C , D
C's Team Member is => D
D's Team Member is => null (he doesn't have any team members yet)
使用SQL查询,如何找到“A”的团队成员?
答案 0 :(得分:0)
您可以使用递归SELECT语句,如下所示: -
DECLARE @LeadName CHAR(1) = 'A';
WITH Team AS (
SELECT ID, F_NAME, L_NAME, INTRODUCED_BY FROM mlm
WHERE F_NAME = @LeadName
UNION ALL
SELECT M.ID, M.F_NAME, M.L_NAME, M.INTRODUCED_BY FROM mlm M
JOIN Team T ON M.INTRODUCED_BY = T.ID
)
SELECT * FROM Team WHERE F_NAME <> @LeadName;
此处变量@LeadName
是所需根目录的F_NAME
(在您的情况下为“A”)。