2017-09-09 15 views
0

私は、特定のルートディレクトリの下にあるすべてのファイルのクロール結果を保存するために使用しているMariaDB 10.2.8データベースを持っています。そのためファイル(fileテーブル内)には親ディレクトリ(directoryテーブル)があります。この親ディレクトリは、ディレクトリクロールが開始された元のポイントまで独自の親を持つことができます。私は/homeからクロールを行った場合MariaDB再帰的CTEの順序を逆にする

ので、ファイル/home/tim/projects/foo/bar.pyは親ディレクトリprojectsなどを持っているでしょう親ディレクトリfooを、持っているでしょう。 /home(クロールのルート)にはnullの親があります。

私は次の再帰CTEを持っている:

(予想通り) @FileIDはファイルの主キーであるため、中に結果を返します
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; 

。例えば

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は、もちろん、クロールのルートである)ディレクトリ/metatron/Projects/fresnel/.git/objects/b8内のファイルに対応します。

出力の順序を逆転させる信頼できる方法があります(完全なパスを生成するために一緒に連結したいので)。私はorder by idすることができますが、これは子供が彼らの両親よりも高いIDを持っていることを私が知っているとしても、信頼できるとは感じません。これはいつもCTE 。

答えて

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

(あなたがそれに問題がある場合は、あまりにも、前にSELECT ...を貼り付けます。