代码之家  ›  专栏  ›  技术社区  ›  Ali Sheikhpour

查找最顶级父级的子级

  •  0
  • Ali Sheikhpour  · 技术社区  · 8 年前

    有类似的问题问如何找到一个孩子的顶级家长( this this 还有这个)。我有一个类似的问题,但我想找到一个顶级家长的所有孩子。 This 是类似的问题,但使用wordpress预定义函数。

    样品表:

    id    parent
    1     0
    2     0
    3     1
    4     2
    5     3
    6     3
    7     4
    

    我想选择一个ID,其中最上面的父级等于1。输出应该是3,3的所有子级,我的意思是(5,6),如果有的话,还有更深层的子级。

    我知道我可以用 但是hirearchy可能更复杂,水平更高。

    2 回复  |  直到 8 年前
        1
  •  0
  •   The Impaler    8 年前

    一个简单的“递归CTE”将实现您想要的:

    with n as (
      select id from my_table where id = 1 -- starting row(s)
      union all
      select t.id
        from n
        join my_table t on t.parent_id = n.id
    )
    select id from n;
    

    . 好。。。默认情况下,SQLServer将其限制为128个级别(可以增加到65k)。

        2
  •  0
  •   S3S    8 年前

    既然你没有爬上整个梯子。。。

    select *
    from YourTable
    where parent = (select top 1 parent from YourTable group by parent order by count(parent) desc)
    

    如果您想返回3的父级,因为3是最常列出的,那么您应该使用递归CTE。