Sql 查询 select 同一个 table 中的所有子项

Sql query to select all the sub items in the same table

我有一个 table,其中一列依赖于另一列。 table 我有一些类似于下面的东西

FolderId | ParentFolderID | Name
1        |  null          | ParentFolder 
2        |  1             | Test1
3        |  2             | Test2
4        |  3             | Test3
5        |  null          | Test4
6        |  null          | Test5
7        |  6             | Test6
8        |  5             | Test7

我需要过滤掉指出根文件夹 ID 1 的父文件夹 ID。输出应该如下所示 table:

FolderId | ParentFolderID |Name
1        |  null          |ParentFolder
2        |  1             |Test1
3        |  2             |Test2
4        |  3             |Test3

谢谢和问候,

试试这个

select * from @TableName S 
where S.FolderId in (select ParentFolderId from @TableName) or S.ParentFolderId is not null

尝试以下查询:

WITH CTE1 AS
(
SELECT *
FROM Table1
WHERE ParentFolderID IS NULL
AND FolderID = 1
UNION ALL
SELECT A.*
FROM Table1 A
INNER JOIN CTE1 C
ON A.ParentFolderID = C.FolderID
)
SELECT * FROM CTE1;

dbfiddle Link