sql - 选择递归并排序

标签 sql postgresql recursion recursive-query

我使用下面的查询从上到下递归选择
例如
如果 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/

相关文章:

java - 获取预选结果

sql - 为什么我的 SQL Server 游标非常慢?

php - 尝试让 php 按钮与 SQL 交互,也许是 AJAX?

c - 字符串排列 - 这种回溯递归是如何工作的?

javascript - JS新手: How to properly call a recursive function in an HTML document?

mysql - REPLACE INTO,它是否重新使用 PRIMARY KEY?

Python 和 Psycopg2 |具有不同 WHERE 子句的动态查询

c - 如何访问Postgresql c语言函数中的大对象?

mysql - 关于 Web (http) 请求和可扩展性的数据库并发连接数

java - 我如何在java中递归地重新排列字符串