【问题标题】:Same-table Tree Table Query in SQL ServerSQL Server 中的同表树表查询
【发布时间】:2014-01-23 01:13:33
【问题描述】:

我已经搜索过,但没有找到任何有用的信息。

我在 SQL Server 2005 数据库中有下表:

Parent     Child             Value
----       --------          ---------
America    Mexico            8
America    Canada            1
Asia       Japan             5
Asia       Korea             7
Europe     Spain             0
Europe     Italy             2
Africa     Zimbabwe          1
Mexico     Baja California   0
America    USA               3
USA        California        1
USA        Texas             2

Parent 和 Child 是主键,值不重要 (IMO)。我想创建一个视图,结果如下:

Parent     Child             Value
----       --------          ---------
America    USA               3
USA        California        1
USA        Texas             2

我会搜索 America,结果会递归返回所有嵌套的子节点,无论它有多少,因为我可以包括城市、地区等。

我需要的类似于一些人所说的 BOM 爆炸。

【问题讨论】:

  • 是你想要的那三行还是你遗漏了一堆其他行?
  • 我遗漏了一堆行,如果我想要美国和美国的所有孩子,这三行就是结果集

标签: sql recursion tree common-table-expression


【解决方案1】:

你可以这样做:

with cte as (
       select parent, child
       from t
       union all
       select cte.parent, t.child
       from cte join
            t
            on cte.child = t.parent
     )
select cte.*
from cte
where parent = 'America';

Here 是一个小的 SQL Fiddle 示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-17
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2011-12-18
    相关资源
    最近更新 更多