2

我在这里创建了一个 SQL 小提琴。

基本上,我有 3 个表BaseTable,Files和一个LinkingTable.

Files表有 3 列:PKBaseTableIdRecursiveId(ChildId)。我想要做的是找到给定一个BaseTableId(即ParentId)的所有孩子。棘手的部分是找到孩子的方式是这样的:

ParentId( BaseTable.BaseTableId) 1 并使用它FileIdFiles表中查找 a ,然后使用它FileId在 中查找ChildId( LinkingTable.RecursiveId) LinkingTable,如果该记录存​​在,则使用RecursiveIdinLinkingTable查找表中的下一个FileIdFiles依此类推。

到目前为止,这是我的 CTE:

with CTE as
(
    select lt.FileId, lt.RecursiveId, 0 as [level],
        bt.BaseTableId
    from BaseTable bt
    join Files f
    on bt.BaseTableId = f.BaseTableId
    join LinkingTable lt
    on f.FileId = lt.FileId
    where bt.BaseTableId = @Id
    UNION ALL
    select rlt.FileId, rlt.RecursiveId, [level] + 1 as [level],
        CTE.BaseTableId
    from CTE --??? and this is where I get lost
...
)

= 1的正确输出BaseTableId应该是:

FileId|RecursiveId|level|BaseTableId
  1        1         0        1
  3        2         1        1
  4        3         2        1

表关系

表关系

4

1 回答 1

1

这是一个我认为符合您的标准的递归示例。我ParentId在结果集中添加了一个,对于根/基本文件,它是 NULL,因为它没有父文件。

declare @BaseTableId int;
set @BaseTableId  = 1;

; WITH cteRecursive as (
    --anchor/root parent file
    SELECT null as ParentFileId
        , f.FileId as ChildFileID
        , lt.RecursiveId 
        , 0 as [level]
        , bt.BaseTableId
    FROM BaseTable bt
        INNER JOIN Files f
            on bt.BaseTableId = f.BaseTableId
        INNER JOIN LinkingTable lt
            on f.FileId = lt.FileId
    WHERE bt.BaseTableId = @BaseTableId 

    UNION ALL 

    SELECT cte.ChildFileID as ParentFileID 
        , f.FileId as ChildFileID
        , lt.RecursiveId
        , cte.level + 1 as [level]
        , cte.BaseTableId
    FROM cteRecursive cte
        INNER JOIN Files f on cte.RecursiveId = f.RecursiveId
        INNER JOIN LinkingTable lt ON lt.FileId = f.FileId
)
SELECT * 
FROM cteRecursive
;

@BaseTableID = 1 的结果:

ParentFileId ChildFileID RecursiveId level       BaseTableId
------------ ----------- ----------- ----------- -----------
NULL         1           1           0           1
1            3           2           1           1
3            4           3           2           1

@BaseTableID = 2 的结果:

ParentFileId ChildFileID RecursiveId level       BaseTableId
------------ ----------- ----------- ----------- -----------
NULL         2           1           0           2
NULL         2           4           0           2
2            6           5           1           2
6            7           6           2           2
2            3           2           1           2
3            4           3           2           2
于 2014-06-13T17:16:39.130 回答