T-SQL / SQL Server - 如何递归选择给定父级的所有嵌套子ID?

时间:2017-11-15 11:51:20

标签: sql-server tsql

考虑以下表格和层次结构:

enter image description here

如果我有父(10012, 10013, 10014)的ID(优雅高效),我该如何选择所有子ID 10011

此处ParentId自我引用父文件夹。

3 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @DataSource TABLE
(
    [FolderID] INT
   ,[FolderName] VARCHAR(12)
   ,[ParentID] INT
);

INSERT INTO @DataSource ([FolderID], [FolderName], [ParentID])
VALUES (10011, 'NEw Folder', NULL)
      ,(10012, 'NEw Folder', 10011)
      ,(10013, 'NEw Folder', 10012)
      ,(10014, 'NEw Folder', 10013)
      ,(10021, 'NEw Folder', NULL)
      ,(10022, 'NEw Folder', 10021)
      ,(10023, 'NEw Folder', 10022);

DECLARE @ParentID INT = 10011;

WITH DataSource AS
(
    SELECT *
    FROM @DataSource
    WHERE [FolderID] = @ParentID
    UNION ALL
    SELECT A.*
    FROM DataSource R
    INNER JOIN @DataSource A
        ON R.[FolderID] = A.[ParentID]
)     
SELECT DISTINCT [FolderID]
FROM DataSource
WHERE [FolderID] <> @ParentID;

enter image description here

答案 1 :(得分:0)

使用递归cte

;WITH cte 
AS
(   SELECT
        b.FolderId, b.FolderName, b.ParentiD
    FROM
        table b
    WHERE
        FolderId= 10011
    UNION ALL
    SELECT
        e.FolderId, e.FolderName, e.ParentId
    FROM
        table  e
    INNER JOIN
        cte r ON e.ParentId = r.FodlerId
)
SELECT * FROM cte

答案 2 :(得分:0)

简单的自我加入会帮助你

select e.folderid from table1 e inner join table1 t on e.parentid = t.folderid where t.parentid = 10011

尝试以上查询:)