16

我有一个问题,我无法解决。我知道我想要什么,只是无法在屏幕上显示出来。我有一张看起来像这样的桌子:

Id, PK UniqueIdentifier, NotNull
Name, nvarchar(255), NotNull
ParentId, UniqueIdentifier, Null

ParentId 对 Id 有一个 FK。

我想要完成的是获得我传入的 Id 下面所有 id 的平面列表。

例子:

1   TestName1    NULL
2   TestName2    1
3   TestName3    2
4   TestName4    NULL
5   TestName5    1

树看起来像这样:

-1
  -> -2
       -> -3
  -> -5
-4

如果我现在要 4,我只会得到 4,但如果我要 1,我会得到 1、2、3 和 5。如果我要 2,我会得到 2 和 3,依此类推。

有没有人可以指出我正确的方向。我的大脑被炸了,所以我很感激我能得到的所有帮助。

4

5 回答 5

23
declare @T table(
  Id int primary key,
  Name nvarchar(255) not null,
  ParentId int)

insert into @T values
(1,   'TestName1',    NULL),
(2,   'TestName2',    1),
(3,   'TestName3',    2),
(4,   'TestName4',    NULL),
(5,   'TestName5',    1)

declare @Id int = 1

;with cte as
(  
  select T.*
  from @T as T
  where T.Id = @Id
  union all
  select T.*
  from @T as T
    inner join cte as C
      on T.ParentId = C.Id
)
select *
from cte      

结果

Id          Name                 ParentId
----------- -------------------- -----------
1           TestName1            NULL
2           TestName2            1
5           TestName5            1
3           TestName3            2
于 2011-04-13T12:55:06.017 回答
6

这是一个工作示例:

declare @t table (id int, name nvarchar(255), ParentID int)

insert @t values
(1,   'TestName1',    NULL),
(2,   'TestName2',    1   ),
(3,   'TestName3',    2   ),
(4,   'TestName4',    NULL),
(5,   'TestName5',    1   );

; with rec as
        (
        select  t.name
        ,       t.id as baseid
        ,       t.id
        ,       t.parentid
        from    @t t
        union all
        select  t.name
        ,       r.baseid
        ,       t.id
        ,       t.parentid
        from    rec r
        join    @t t
        on      t.ParentID = r.id
        )
select  *
from    rec
where   baseid = 1

您可以过滤baseid,其中包含您要查询的树的开始。

于 2011-04-13T12:53:31.003 回答
3

Try this:

WITH RecQry AS
(
    SELECT *
      FROM MyTable
    UNION ALL
    SELECT a.*
      FROM MyTable a INNER JOIN RecQry b
        ON a.ParentID = b.Id
)
SELECT *
  FROM RecQry
于 2011-04-13T12:51:00.327 回答
0

Here is a good article about Hierarchy ID models. It goes right from the start of the data right through to the query designs.

Also, you could use a Recursive Query using a Common Table Expression.

于 2011-04-13T12:48:59.483 回答
0

I'm guessing that the easiest way to accomplish what you're looking for would be to write a recursive query using a Common Table Expression:

MSDN - Recursive Queries Using Common Table Expressions

于 2011-04-13T12:49:40.803 回答