1
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]
    union all
    select Folder_Table.folder_id,Folder_Table.parent_id,Folder_Table.folder_name
    from cte 
        join Folder_Table on cte.parent_id = Folder_Table.folder_id
)
SELECT distinct * FROM cte

在这个查询中,如果有孩子,我需要获取项目的级别和该级别的孩子的数量

4

2 回答 2

2

获取Level很容易:

WITH cte(folder_id, parent_id, folder_name, level)
AS
(
    SELECT
       folder.folder_id, folder.parent_id, folder.folder_name, Level = 0
    FROM 
       Folder_Table [folder] 
    INNER JOIN 
       File_Table [file] on [folder].[folder_id] = [file].[folder_id]

    UNION ALL

    SELECT 
       Folder_Table.folder_id, Folder_Table.parent_id, Folder_Table.folder_name, CTE.Level + 1
    FROM
       cte 
    INNER JOIN 
       Folder_Table on cte.parent_id = Folder_Table.folder_id
)
SELECT DISTINCT * FROM cte

但是计算孩子的数量相当棘手——你几乎必须“预览”任何给定级别的下一个级别;我想不出任何简单的方法来做到这一点,对不起。

于 2012-10-15T17:23:12.290 回答
0

我假设您只想在文件夹中有文件时才包括孩子的数量。另外,我假设最顶层的文件夹将具有与 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
于 2012-10-15T23:16:08.180 回答