select 递归和排序依据

select recursive and order by

我使用下面的查询 select 从上到下递归
例如
如果 tagId 是 1 将得到行 1 > 3,4, > 5 现在工作正常,
但我想知道如何在每个级别(相同的父 ID)通过 "Name" 获取结果顺序 get rows 1 > 4,3 > 5 ?

我想在 SELECT * FROM "Tag" WHERE "TagId" = 之后添加 ORDER BY "Name" 但没有用。
如果在 SELECT * FROM tag_tree 之后添加,那么混乱级别将变为 1,4,5,3 不是我想要的。

CREATE TABLE IF NOT EXISTS "Tag"(
"TagId" SERIAL NOT NULL,
"ParentTagId" integer,
"Name" varchar,
PRIMARY KEY ("TagId")
);

TagId | ParentTagId | Name |
1     |             | a   |
2     |             | b   |
3     | 1           | b   |
4     | 1           | a   |
5     | 3           | a   |


var query = 'WITH RECURSIVE tag_tree AS (
  (
    SELECT * FROM "Tag" WHERE "TagId" = 
  )
  UNION ALL
  SELECT child.* FROM "Tag" child
    JOIN tag_tree parent on parent."TagId" = child."ParentTagId"
)
SELECT * FROM tag_tree';

添加 ORDER BYcoalesce():

WITH RECURSIVE tag_tree AS (
  (
    SELECT * FROM "Tag" WHERE "TagId" = 1
  )
  UNION ALL
  SELECT child.* FROM "Tag" child
    JOIN tag_tree parent on parent."TagId" = child."ParentTagId"
)
SELECT * FROM tag_tree
ORDER BY coalesce("ParentTagId", 0), "Name";

 TagId | ParentTagId | Name 
-------+-------------+------
     1 |             | a
     4 |           1 | a
     3 |           1 | b
     5 |           3 | a
(4 rows)

对于the documentation

The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.

在这种情况下,函数将 null 更改为 0