【问题标题】:How to find root-nodes如何找到根节点
【发布时间】:2012-05-18 09:08:37
【问题描述】:
id  Parant_ID       sort_nm    Scheme_Name
5   5               CAMPA      CAMPA
6   5               NPV        Net Present Value
7   5               CA         Compensatory Afforestation
8   6               ACA        Additional Compensatory  Afforestation
43  8               asd        asdasd
45  45              new        new
46  45              asdaasdas  asdasdasdas

我在 SQL Server 中有上述树形结构。
我想知道每个节点的根节点id。

【问题讨论】:

  • 您好,欢迎来到 StackOverflow!请注意,您的问题需要更多细节,即:尝试了什么?什么有效?什么没有? (另请注意,您的图是有向图,而不是树 - ID 5 循环回自身,这是有意的吗?)
  • 就个人而言,我会创建一个列来存储所有记录的根父 ID,并在更改记录时更新它。它没有严格规范化,但它节省了一个丑陋的查询。
  • @Polynomial:嵌套集可能是更好的解决方案;也标准化:sideralis.org/baobab 不确定 OP 是否可以更改其数据库结构。
  • 请记得查看最有帮助的答案 - 这样其他人会很乐意帮助您解决更多问题。 :)
  • stackoverflow.com/questions/15732347/…
    请解决我的这个问题

标签: sql-server-2008


【解决方案1】:

您可以使用recursive CTE。从根开始,递归携带RootID。

with C as
(
  select id,
         Parant_ID,
         sort_nm,
         Scheme_Name,
         id as RootID
  from YourTable
  where id = Parant_ID
  union all
  select T.id,
         T.Parant_ID,
         T.sort_nm,
         T.Scheme_Name,
         C.RootID
  from YourTable as T
    inner join C
      on T.Parant_ID = C.id
  where T.id <> T.Parant_ID
)
select *
from C

SE-Data

【讨论】:

  • 我很佩服你在 sql +1 方面的知识。
  • @RoyiNamir - 啊,现在我想起来了。我感觉我已经回答了similar question a while back :)。
  • 从根而不是叶子开始的想法让我抓狂:“他是怎么开始认为应该从根而不是叶子开始的......”
  • 附注昨天我问了另一个有趣的问题(IMO)......也许你可以用一个新的解决方案来启发? stackoverflow.com/questions/10638176/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 2020-11-13
  • 2020-06-06
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 2021-06-06
相关资源
最近更新 更多