我有一個MariaDB 10.2.8數據庫,我正在使用該數據庫來存儲抓取特定根目錄下的所有文件的結果。所以一個文件(在file
表中)有一個父目錄(在directory
表中)。這個父目錄可能有它自己的父母,直到目錄爬行開始的原始點。逆轉MariaDB遞歸CTE的順序
所以,如果我從/home
做了爬行,文件/home/tim/projects/foo/bar.py
將有一個父目錄foo
,這將有一個父目錄projects
等。 /home
(抓取的根目錄)將有一個null
父級。
我已經得到了下面的遞歸CTE:
with recursive tree as (
select id, name, parent from directory where id =
(select parent from file where id = @FileID)
union
select d.id, d.name, d.parent from directory d, tree t
where t.parent = d.id
) select name from tree;
其(預期)返回順序,其中@FileID
是該文件的主鍵的結果。例如
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.2.8-MariaDB-10.2.8+maria~jessie-log mariadb.org binary distribution
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> use inventory;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [inventory]> with recursive tree as (
-> select id, name, parent from directory where id =
-> (select parent from file where id = 3790)
-> union
-> select d.id, d.name, d.parent from directory d, tree t
-> where t.parent = d.id
->) select name from tree;
+----------+
| name |
+----------+
| b8 |
| objects |
| .git |
| fresnel |
| Projects |
| metatron |
+----------+
6 rows in set (0.00 sec)
MariaDB [inventory]> Bye
[email protected]:~$
因此,在這種情況下,文件ID 3790對應的目錄/metatron/Projects/fresnel/.git/objects/b8
一個文件(/metatron
是,當然,抓取的根)。
是否有可逆的方法來顛倒輸出的順序(因爲我想將它們聯合起來以產生完整的路徑)。我可以order by id
,但這並不可靠,因爲即使我知道,在這種情況下,孩子的身份證明比他們的父母更高,但我無法保證在任何情況下我都會使用CTE 。