2
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

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

任何人都可以帮忙吗?

4

2 回答 2

3

如果您使用的是 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
;
于 2009-10-22T01:08:25.267 回答
0

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


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

于 2009-10-31T00:15:09.653 回答