在层次结构SQL中查找所有子项

时间:2014-08-13 15:17:21

标签: sql sql-server

我有一个类似于这个

的数据库层次结构
LHID | location     | parent
------------------------------
1    | Trim         | NULL
2    | Trim - South | Trim
3    | South-1      | Trim - South

我需要做的是选择Trim - South的所有孩子。它非常深,有大约100个孩子的位置,我已经找到了递归方式,但没有运气复制它们。我知道通过递归方式选择所有子项的逻辑,因为我已经在其他语言中执行了类似的过程,从来没有使用过SQL,所以我很难掌握它的确切必要语法。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用递归CTE:

WITH CTE 
AS(
  SELECT 1 AS relationLevel, child.*
  FROM dbo.TableName child
  WHERE child.parent = 'Trim - South'

  UNION ALL

  SELECT relationLevel+1, parent.*
  FROM CTE nextOne
  INNER JOIN  dbo.TableName parent ON parent.parent = nextOne.location
)
SELECT * FROM CTE ORDER BY relationLevel

结果:

RELATIONLEVEL   LHID    LOCATION    PARENT
1                3      South-1     Trim - South
1                4      South-2     Trim - South
2                4      South-2-1   South-2

DEMO

也许你想从父母到孩子的travserse,然后使用:

WITH CTE 
AS(
  SELECT 1 AS relationLevel, parent.*
  FROM dbo.TableName parent
  WHERE parent.location = 'Trim - South'  

  UNION ALL

  SELECT relationLevel + 1, child.*
  FROM CTE nextOne
  INNER JOIN  dbo.TableName child ON child.parent = nextOne.location
)   
SELECT * FROM CTE ORDER BY relationLevel

结果:

RELATIONLEVEL   LHID    LOCATION    PARENT
1               2    Trim - South   Trim
2               3    South-1        Trim - South
2               4    South-2        Trim - South
3               4    South-2-1      South-2

DEMO