gpt4 book ai didi

sql - PostgreSQL 递归与

转载 作者:行者123 更新时间:2023-11-29 11:13:20 25 4
gpt4 key购买 nike

我需要有关递归查询的帮助。假设下表:

CREATE TEMPORARY TABLE tree (
id integer PRIMARY KEY,
parent_id integer NOT NULL,
name varchar(50)
);

INSERT INTO tree (id, parent_id, name) VALUES (3, 0, 'Peter'), (2,0, 'Thomas'), (5,2, 'David'), (1, 0, 'Rob'), (8, 0, 'Brian');

我可以使用以下查询检索所有人及其子女的列表:

WITH RECURSIVE recursetree(id, parent_id) AS (
SELECT id, parent_id FROM tree WHERE parent_id = 0
UNION
SELECT t.id, t.parent_id
FROM tree t
JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * FROM recursetree;

如何按顺序列出它们,并按名称对第一级项目进行排序?例如,所需的输出将是:

id, parent_id, name    
8, 0, "Brian"
3, 0, "Peter"
1, 0; "Rob"
2, 0, "Thomas"
5, 2, " David"

谢谢,

**编辑。请注意,添加 ORDER BY 将不起作用:**

WITH RECURSIVE recursetree(id, parent_id, path, name) AS (
SELECT
id,
parent_id,
array[id] AS path,
name
FROM tree WHERE parent_id = 0
UNION ALL
SELECT t.id, t.parent_id, rt.path || t.id, t.name
FROM tree t
JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * FROM recursetree ORDER BY path;

以上将保留父子关系( child 跟随他们的 parent ),但应用任何其他 ORDER BY 子句(即:名称 - 就像一些人建议的那样)将导致结果失去它的父子关系。

最佳答案

另请参阅这篇关于 PostgreSQL 中 CTE 的(已翻译)文章:wiki.phpfreakz.nl

编辑:试试这个,使用数组:

WITH RECURSIVE recursetree(id, parent_ids, firstname) AS (
SELECT id, NULL::int[] || parent_id, name FROM tree WHERE parent_id = 0
UNION ALL
SELECT
t.id,
rt.parent_ids || t.parent_id,
name
FROM tree t
JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * FROM recursetree ORDER BY parent_ids;

关于sql - PostgreSQL 递归与,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3307480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com