【问题标题】:SQL - Find the parent of the tree structure [duplicate]SQL - 查找树结构的父级[重复]
【发布时间】:2021-07-29 17:17:58
【问题描述】:

我有一个这样的表, parent_id=0 表示当前行是主父:

---------------------
class_id | parent_id
---------------------
    10        0
    11        10
    12        11
    13        12

我想获取其主要父类 class_id 等于 10 的行 但是当我使用SELECT 语句时,它只返回一行,因为它具有层次结构。

SELECT class_id FROM TABLE WHERE parent_id = 10

【问题讨论】:

    标签: mysql sql join select inner-join


    【解决方案1】:

    您可以使用典型的递归 CTE 从节点 10 开始遍历图形。例如:

    with recursive
    n as (
      select * from t where class_id = 10
     union all
      select t.*
      from n
      join t on t.parent_id = n.class_id
    )
    select * from n
    

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      相关资源
      最近更新 更多