【问题标题】:Find full path of a file in a file system在文件系统中查找文件的完整路径
【发布时间】:2016-05-14 21:34:53
【问题描述】:

我有一个这样的文件系统:

C Drive - Docements - (empty)
        - Music - Rock - a.mp3
                - Jazz - SmoothJazz - b.mp3
        - Photo - (empty)
D Drive - (empty)

每个文件或目录都有一个 id,以及它的父 id。现在给定一个文件名或目录名,如何找到它的完整路径?

我的算法是:

Recursively (
    if (parent id is not null)
        find parent id in the table
)

【问题讨论】:

    标签: sql postgresql recursive-cte


    【解决方案1】:

    您可以为此使用递归查询。假设一个表 file 包含 idnameparent 列:

    WITH RECURSIVE t AS
    (SELECT id, name, parent, name as path
    FROM file
    WHERE id=3
    UNION ALL
    SELECT si.id,si.name,
    si.parent,
    si.name || '/' || sp.path as path
    FROM file As si
    INNER JOIN t AS sp
    ON (si.id = sp.parent)
    )
    SELECT *
    FROM t where parent is null
    ORDER BY path
    

    这将为您提供path 中指向id=3 文件的完整路径。可能不是最有效的查询。

    【讨论】:

      猜你喜欢
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 2016-05-15
      • 2016-10-07
      • 2022-06-15
      相关资源
      最近更新 更多