나는 SQL 바이올린 here을 만들었습니다.교대 테이블을 사용하는 순환 CTE
기본적으로 테이블 3 개는 BaseTable
, Files
및 LinkingTable
입니다.
Files
테이블에는 PK
, BaseTableId
, RecursiveId
(ChildId)의 세 열이 있습니다. 내가하고 싶은 일은 BaseTableId
(즉, ParentId)이 주어진 모든 아동을 찾는 것입니다. 까다로운 부분은 아이들이이 같은 작품을 발견하는 방법이다 :
FileId
가 보는 것을 사용 ParentId
(BaseTable.BaseTableId
) 1을 가지고 다음의 Files
테이블에 FileId
을 찾아 볼 것을 사용하십시오 ChildId
(LinkingTable.RecursiveId
)가 LinkingTable
인 경우 해당 레코드가 존재하면 의 RecursiveId
을 사용하여 Files
테이블의 다음 FileId
을 찾습니다.
이는 지금까지 내 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
표 관계
샘플 데이터뿐만 아니라 원하는 결과가 문제를 설명하기위한 매우 유용 할 것입니다. –
@ GordonLinoff 질문 상단에 바이올린 링크가 있습니다 – SOfanatic
SQLFiddle 열 이름이 위의 예제 쿼리에서 열 이름과 일치하면 유용합니다. 현재 SQLFiddle의 BaseTable에는 UniqueId int, FKId int 열이 있습니다. 나는 UniqueId = BaseTableId이고 FKId = FileId라고 가정하고 있습니까? – BateTech