【问题标题】:Reversing the order of a MariaDB recursive CTE反转 MariaDB 递归 CTE 的顺序
【发布时间】:2017-09-09 09:39:26
【问题描述】:

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

因此,如果我从/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;

which(如预期)按顺序返回结果,其中@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:~$

所以在这种情况下,文件 ID 3790 对应目录 /metatron/Projects/fresnel/.git/objects/b8 中的一个文件(/metatron 当然是爬取的根目录)。

是否有可靠的方法来反转输出的顺序(因为我想将它连接在一起以生成完整路径)。我可以order by id 但这并不可靠,因为即使我知道,在这种情况下,孩子的 ID 比他们的父母高我不能保证在我想使用的每种情况下都会如此一个 CTE。

【问题讨论】:

    标签: recursion mariadb common-table-expression


    【解决方案1】:
    (
         your-current-query
    ) ORDER BY ...;
    

    (如果您对此有问题,也可以在前面加上SELECT ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-23
      • 2019-06-25
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 2019-06-20
      • 2011-04-25
      • 2021-05-31
      相关资源
      最近更新 更多