2013-12-13 109 views
0

我有一個像這樣的表格和一些行數。SQL中的構造樹

ID | REfID | Name 
------------------ 
1 |  | name1  
2 | 5 | name2 
3 | 4 | name3 
4 | 1 | name4 
5 | 3 | name2 

如何根據ID和RefID在SQL中查詢子級的子級和子級。例如,當我請ID = 5,

它應該返回行(ID)的3,4,1

我創建查詢使用LINQ,它工作正常。

List<Employee> empList = new List<Employee>() 
      { 
       new Employee() { ID=1,Name = "Name1" }, 
       new Employee() { ID=2,Name = "Name1" ,REFID = 5}, 
        new Employee() { ID=3,Name = "Name1" ,REFID = 4}, 
        new Employee() { ID=4,Name = "Name1" ,REFID = 1}, 
        new Employee() { ID=5,Name = "Name1" ,REFID = 3}, 

      }; 

     // 5 = >3 => 4 => 1. 

     Dictionary<int, Employee> employeeByID = empList.ToDictionary(x => x.ID); 
     List<Employee> result = new List<Employee>(); 
     this.findChild(employeeByID[5], employeeByID, ref result); 

public void findChild(Employee emp, Dictionary<int, Employee> source,ref List<Employee> result) 
     { 
      result.Add(emp); 

      if (source.ContainsKey(emp.REFID)) 
      { 
       Employee child = source[emp.REFID]; 
       this.findChild(child ,source, ref result); 

      } 
     } 

我需要創建一個等效的SQL查詢。如何歸檔這個?

回答

1

它尚未解決您的問題,但給你一些工作。遞歸CTE你可以跟蹤所有記錄父子關係(我假設你使用SQL Server):

drop table #temp 
GO 
select 
    * 
into #temp 
from (
    select 1 as id, null as refid, 'name1' as name union all 
    select 2, 5, 'name2' union all 
    select 3, 4, 'name3' union all 
    select 4, 1, 'name4' union all 
    select 5, 3, 'name2' 
) x 
GO 

;with cte as (
    select 
     id, refid, name, 
     idpath = cast(id as varchar(255)) 
    from #temp 
    where 1=1 
     and refid is null 
union all 
    select 
     t.id, t.refid, t.name, 
     idpath = cast(c.idpath+'|'+cast(t.id as char(1)) as varchar(255)) 
    from #temp t 
    join cte c 
     on c.id=t.refid 
) 

select 
    * 
from cte