在this answer中,我询问了如何获取所有子节点以及对根节点的引用。现在我意识到我还需要相反的事情:
我希望拥有所有节点和所有父节点。
所以在这个简单的树中:
1 - 2 - 3
L - 4 - 5
L - 6
7 - 8
我想
1 1;
2 2;
2 1;
3 3;
3 2;
3 1;
4 4;
4 2;
4 1;
5 5;
5 4;
5 2;
5 1;
6 6;
6 4;
6 2;
6 1;
7 7;
8 8;
8 7;
(顺序并不重要)
这是获取相反的查询(来自父级获取所有子项)。我试着玩它但找不到解决方案。你能建议吗?
-- get all childs of all parents
WITH q AS
(
SELECT ID_CUSTOMER, ID_CUSTOMER AS root_customer
FROM CUSTOMERS c
UNION ALL
SELECT c.ID_CUSTOMER, q.root_customer
FROM q
JOIN CUSTOMERS c
ON c.ID_PARENT_CUSTOMER = q.ID_CUSTOMER
)
SELECT *
FROM q
答案 0 :(得分:3)
此查询构建邻接列表的transitive closure
:所有祖先 - 后代对的列表。
因为它将返回每个祖先的所有后代,反之亦然:对于每个后代,它将返回其所有祖先。
因此,无论遍历顺序如何,这个查询都会返回所有可能的组合:无论您是孩子的连接父母还是其他方式都无关紧要。
让我们测试一下:
WITH customers (id_customer, id_parent_customer) AS
(
SELECT *
FROM (
VALUES (1, NULL),
(2, 1),
(3, 2),
(4, 2),
(5, 4),
(6, 4),
(7, NULL),
(8, 7)
) t (a, b)
),
q AS
(
SELECT ID_CUSTOMER, ID_CUSTOMER AS root_customer
FROM CUSTOMERS c
UNION ALL
SELECT c.ID_CUSTOMER, q.root_customer
FROM q
JOIN CUSTOMERS c
ON c.ID_PARENT_CUSTOMER = q.ID_CUSTOMER
)
SELECT *
FROM q
ORDER BY
id_customer, root_customer DESC
答案 1 :(得分:0)
with q (
select id_customer, id_parent_customer from customers
union all
select id_customer, id_parent_customer from customers
join q on customers.id_parent_customer = q.id_customer
) select * from q