【问题标题】:Parent - Child sql query父 - 子 sql 查询
【发布时间】:2010-12-08 22:26:09
【问题描述】:
id  parent_id
1   0
2   0
3   2
4   0
5   1
6   0

我需要一个返回父行 (parent_id=0) 后跟其子行的查询:

  1. 第一父母
  2. 第一父母的所有孩子
  3. 第二个父母
  4. 第二个父母的所有孩子
  5. 第三父母
  6. 第四个父母

预期结果:按 id 排序

id   parent_id
-------------------------------------------
1    0 (first parent)
5    1     (all children of first parent)
2    0 second parent
3    2     (all children of second parent)
4    0 third parent
6    0 fourth parent

我可以使用父母的联合,然后是所有孩子 但这给了我父母,然后是孩子。 我需要父母和立即的孩子。

有人可以帮忙吗?

【问题讨论】:

    标签: sql hierarchical


    【解决方案1】:

    如果您使用的是 SQL Server 2005+,则可以使用递归 CTE,确保在最后维护一个可以排序的字段。

    试试这个:

    declare @t table (id int, parent_id int)
    insert @t
    select 1,0
    union all select 2,0
    union all select 3,2
    union all select 4,0
    union all select 5,1
    union all select 6,0
    ;
    
    with tree as (
    select t.*, convert(varbinary(max),t.id) as ordered
    from @t t
    where parent_id = 0
    union all
    select t.*, ordered + convert(varbinary(max),t.id)
    from tree base
     join
     @t t
     on t.parent_id = base.id
     )
    select * 
    from tree
    order by ordered
    ;
    

    【讨论】:

    • 这在我的示例表上不起作用你能写出我上面指定的输出作为我的预期结果的查询吗?谢谢
    • 我的意思是 CTE 首先给了我所有的父行。然后是所有的孩子。不是第一个父母,而是它的孩子,其次是第二个父母和它的孩子,依此类推
    • 我正在寻找用于显示此帖子及其 cmets 的结果。父评论,然后是它的回复(孩子),然后是另一个评论和它的回复。回复是父母评论的孩子。
    • 这个问题的关键是用于排序的列。我确定我的查询有效,只需将 @t 替换为您拥有的表即可。
    • 简单联合在稍微调整查询后给了我想要的结果。我认为按列排序是关键
    【解决方案2】:

    这可以使用两个临时表和三个变量来完成。

    
    CREATE TABLE #Parents
    (
    RowId bigint identity(1,1),
    Id    bigint
    )
    
    

    CREATE TABLE #Results ( RowId bigint identity(1,1), Id bigint, ParentId bigint )

    DECLARE @Count1 bigint DECLARE @Count2 bigint DECLARE @ParentId bigint

    INSERT INTO #Parents SELECT Id FROM MyTable WHERE ParentId = 0 ORDER BY Id

    SET @Count1 = 0 SELECT @Count2 = MAX(RowId) FROM #Parents

    WHILE @Count1 < @Count2 BEGIN SET @Count1 = @Count1 +1 SELECT @ParentId = Id FROM #Parents WHERE RowId = @Count1 INSERT INTO #Results (Id, ParentId) VALUES (@Count1, 0) INSERT INTO #Results (Id, ParentId) SELECT ID, ParentId FROM MyTable WHERE ID = @Count1 ORDER BY Id END

    SELECT Id, ParentId FROM #Results ORDER BY RowId

    DROP TABLE #Results DROP TABLE #Parents

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多