我创建了一个SQL小提琴here。
基本上,我有3个表BaseTable
,Files
和LinkingTable
。
Files
表有3列:PK
,BaseTableId
,RecursiveId
(ChildId)。
我想要做的是找到给BaseTableId
的所有孩子(即ParentId)。
棘手的部分是找到孩子的方式是这样的:
取ParentId
(BaseTable.BaseTableId
)1并使用它在FileId
表格中查找Files
,然后使用FileId
查找ChildId
中的LinkingTable.RecursiveId
LinkingTable
,如果该记录存在,则使用RecursiveId
中的LinkingTable
查找下一个FileId
Files
表等等。
到目前为止,这是我的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
...
)
BaseTableId
= 1的正确输出应为:
FileId|RecursiveId|level|BaseTableId
1 1 0 1
3 2 1 1
4 3 2 1
表关系
答案 0 :(得分: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