0

我有递归查询,它从分层模型返回一些行。有点儿:

files_array := ARRAY
   (WITH RECURSIVE files_to_parent AS (
          SELECT FileID, Name, ParentID
          FROM File
          WHERE FileID = file_id
       UNION ALL
          SELECT F.FileID, F.Name, F.ParentID
          FROM files_to_parent ftp, File F
          WHERE F.FileID = FTP.ParentID
    )
    SELECT Name FROM files_to_parent);

如何反转 SELECT 查询的结果?

PS:我不能按 ID 订购,父母的 id 可以或多或少然后在孩子。

4

1 回答 1

1

您必须添加一个显式ORDER BY子句才能获得特定顺序:

WITH RECURSIVE files_to_parent AS (
      SELECT FileID, Name, ParentID,
             1 AS recursion_depth
      FROM File
      WHERE FileID = file_id
   UNION ALL
      SELECT F.FileID, F.Name, F.ParentID,
             ftp.recursion_depth + 1
      FROM files_to_parent ftp
         JOIN File F ON F.FileID = FTP.ParentID
)
SELECT Name
FROM files_to_parent
ORDER BY recursion_depth DESC;
于 2019-01-31T12:47:37.630 回答