我假设您只想在文件夹中有文件时才包括孩子的数量。另外,我假设最顶层的文件夹将具有与 parent_id 相同的 folder_id。
WITH cte (folder_id, parent_id, folder_name) AS
(
SELECT folder.folder_id, folder.parent_id, folder.folder_name
FROM Folder_Table [folder] JOIN File_Table [file] ON [folder].[folder_id] = [file].[folder_id]
WHERE [folder].parent_id = [folder].folder_id
UNION ALL
SELECT folder.folder_id, folder.parent_id, folder.folder_name
FROM cte JOIN Folder_Table [folder] ON cte.folder_id = folder.parent_id
WHERE folder.parent_id != folder.folder_id
)
SELECT parent_id, COUNT(1) as [Number of children]
FROM cte
WHERE folder_id != parent_id
GROUP BY parent_id
请注意,当该文件夹中没有文件时,查询不会返回父文件夹,但是通过在 Folder_Table 和 File_Table 之间的连接中使用 LEFT OUTER JOIN 来更改这一点相当容易
要获取级别,它将与上面的查询非常相似:
WITH cte (folder_id, parent_id, folder_name, level) AS
(
SELECT folder.folder_id, folder.parent_id, folder.folder_name, 0
FROM Folder_Table [folder] JOIN File_Table [file] ON [folder].[folder_id] = [file].[folder_id]
WHERE [folder].parent_id = [folder].folder_id
UNION ALL
SELECT folder.folder_id, folder.parent_id, folder.folder_name, level+1
FROM cte JOIN Folder_Table [folder] ON cte.folder_id = folder.parent_id
WHERE folder.parent_id != folder.folder_id
)
SELECT * FROM cte