SQL Server内部连接到该查询再次内部连接相同

时间:2017-08-15 08:58:54

标签: sql-server join

我们正在与MLM项目合作。这个项目的基本思路就像

  • A由
  • 引入
  • B由A
  • 引入
  • C由B
  • 引入
  • D由C
  • 引入

我的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”的团队成员?

1 个答案:

答案 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”)。