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查詢。如何歸檔這個?