【问题标题】:Get all of child nodes in a hierarchical data in SQL在 SQL 中获取分层数据中的所有子节点
【发布时间】:2018-09-26 20:17:14
【问题描述】:

我有以下sql表:

id   parent_id
1    null
2    1
3    4
4    8
5    1
6    2
7    6
8    null

如何获取某个特定节点的所有子节点? 例如 id = 1:

1 2 5 6 7

id = 8

8 4 2

【问题讨论】:

  • 什么数据库平台??
  • 任何常见的 rdbms 平台,sql 或 pgSQL

标签: sql postgresql recursion common-table-expression


【解决方案1】:

我在另一个博客中找到了,希望对其他人有所帮助:

with RECURSIVE cte(id,parent_id) as (
  select
    id,
    parent_id
  from forum
  where id = 2
  UNION ALL
  select
    forum.id,
    forum.parent_id
  from forum
    inner join cte on forum.parent_id = cte.id
)
select * from cte

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2011-09-10
    相关资源
    最近更新 更多