我使用下面的查询从上到下递归选择
例如
如果 tagId
为 1 将得到行 1 > 3,4, > 5
现在工作正常,
但我想知道如何在每个级别(相同的父 ID)按“名称”获取结果顺序获取行 1 > 4,3 > 5
?
我想在 SELECT * FROM "Tag"WHERE "TagId"= $1
之后添加 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" = $1
)
UNION ALL
SELECT child.* FROM "Tag" child
JOIN tag_tree parent on parent."TagId" = child."ParentTagId"
)
SELECT * FROM tag_tree';
最佳答案
使用 coalesce()
添加 ORDER BY
:
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
。
关于sql - 选择递归并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33446599/