2010-11-15 122 views
2

我有这样的结构表。如何选择父母ID

ElementId | ParentId 
------------------- 
1   | NULL 
2   | 1 
3   | 2 
4   | 3 

假设当前元素有Id 4.我想选择所有的父标识符。 结果应该是:3,2,1

我该怎么办呢? DB是MSSQL

回答

2

您可以使用递归查询此:http://msdn.microsoft.com/en-us/library/aa175801(SQL.80).aspx

您可以使用它像这样:

with Hierachy(ElementID, ParentID, Level) as (
    select ElementID, ParentID, 0 as Level 
    from table t 
    where t.ElementID = X -- insert parameter here 
    union all 
    select t.ElementID, t.ParentID, th.Level + 1 
    from table t 
    inner join Hierachy th 
    on t.ParentId = th.ElementID 
) 
select ElementID, ParentID 
from Hierachy 
where Level > 0 
+1

它切换p这里参考t.ParentId = th.ElementID – 2010-11-15 12:48:30

1

我想这可能是最容易做到以下几点:

while parent != NULL 
    get parent of current element 

我想不出在普通的SQL这样做的任何方式,不会对较大的数据库引起的问题。

-1
如果你想纯SQL尝试

select ParentId from myTable Desc 

,将在MySQL工作...您可能需要修改Desc(按降序排列)部分