从结构树中返回父id

时间:2014-10-22 11:59:43

标签: tsql sql-server-2012 recursive-query

我正在尝试获取与父母相关的所有子ID(多级)。我以为使用Recursive会做的伎俩,尝试查询它没有返回预期的结果,我甚至不确定这是写这种方式或我出错的地方。

预期结果是返回指定地点的所有城市和县。

例如,如果我传递了英格兰的id(id = 1),我想返回与之关联的所有id。它可以达到4-5级关联

例如

Id      Location
-----  ---------------
1      England
3      London            (as its associated with England)         
5      Ealing            (as associated with London)
6      Westminster       (as associated with London)
7      Camden            (as associated with London)
8      Barnet            (as associated with London)

。 。

SQL Fiddle example

有人可以指出我正确的方向如何解决这个问题。这是解决这个问题的正确方法吗?

感谢。

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

你正朝着正确的方向前进。

考虑我已经取得的成果:

;WITH locationFamily AS
(
    SELECT   id
            ,location_name 
            ,parent_id
            ,0 as level
    FROM location
    WHERE parent_id IS NULL
    and id = 1
    UNION ALL 
    SELECT   ls.id
            ,ls.location_name 
            ,ls.parent_id
            ,level + 1
    FROM location   ls
    INNER JOIN locationFamily  lf ON ls.parent_id= lf.id
)
SELECT *
FROM locationFamily 

将id条件移动到CTE中的第一个选择,更改id连接的别名。