2016-05-14 185 views
1

我有一個文件系統是這樣的:查找文件的完整路徑文件系統

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

每個文件或目錄有一個id,和其父的身份證。現在給出一個文件名或目錄名,你如何找到它的完整路徑?

我的算法是:

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

回答

1

您可以使用遞歸查詢此。假設一臺fileparentidname,:

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 

這將使你在pathid=3該文件的全路徑。可能不是最有效的查詢。

+0

這工作得很好。謝謝 –