颠倒MariaDB递归CTE的顺序

时间:2017-09-09 09:39:27

标签: recursion mariadb common-table-expression

我有一个MariaDB 10.2.8数据库,我用它来存储特定根目录下所有文件的爬网结果。所以文件(在directory表中)有一个父目录(在/home表中)。此父目录可能有自己的父目录,依此类推,直到目录爬网开始的原始点。

因此,如果我从/home/tim/projects/foo/bar.py进行了抓取,则文件foo将具有父目录projects,该目录将具有父目录/home,依此类推。 null(抓取的根目录)将拥有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; 个父级。

我得到了以下递归CTE:

@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 tim@merlin:~$ 是文件的主键。 e.g。

/metatron/Projects/fresnel/.git/objects/b8

因此,在这种情况下,文件ID 3790对应目录/metatron中的文件(order by id当然是爬网的根目录。)

是否有一种可靠的方法来反转输出的顺序(因为我想将它连接在一起以产生完整的路径)。我可以{{1}}但这并不可靠,因为即使我知道,在这种情况下,孩子的身份证明会比他们的父母更高,但我无法保证这种情况始终如此。在任何情况下我都想使用CTE。

1 个答案:

答案 0 :(得分:-1)

(
     your-current-query
) ORDER BY ...;

(如果您遇到问题,请将SELECT ...放在前面。