在postgres递归查询中获取child的所有祖先
Get all ancestors of a child in postgres recursive query
我正在尝试通过加入另一个 table 来获取 child 的所有相关祖先的更多信息。
我是后端新手,所以递归 cte 很难理解。
查找SQLFiddlehere
我有数据:product_id,user_id
我需要的资料:
user_id
master_id
cost
id(john_snow)
null
4
id(bran_stark)
id(john_snow)
6
id(arya_stark)
id(bran_stark)
8
id(sansa_stark)
id(arya_stark)
10
这样我就可以为各自的用户增加利润,并以最低成本作为公司利润。
A RECURSIVE
CTE 正是您要找的。乍一看可能会让人困惑,但经过一些练习后,它就会变得不言自明。最后,它只是一个 UNION
,查询略有不同:
WITH RECURSIVE get_ancestor(child,parent,cost) AS (
SELECT r.user_id,r.parent_id,c.cost FROM user_relation r
JOIN product_cost c ON c.user_id = r.user_id
UNION
SELECT g.child,g.parent,c.cost FROM get_ancestor g
JOIN user_relation r ON r.user_id = g.child
JOIN product_cost c ON c.user_id = r.user_id
)
SELECT * FROM get_ancestor;
演示:SQL Fiddle
我正在尝试通过加入另一个 table 来获取 child 的所有相关祖先的更多信息。 我是后端新手,所以递归 cte 很难理解。
查找SQLFiddlehere
我有数据:product_id,user_id
我需要的资料:
user_id | master_id | cost |
---|---|---|
id(john_snow) | null | 4 |
id(bran_stark) | id(john_snow) | 6 |
id(arya_stark) | id(bran_stark) | 8 |
id(sansa_stark) | id(arya_stark) | 10 |
这样我就可以为各自的用户增加利润,并以最低成本作为公司利润。
A RECURSIVE
CTE 正是您要找的。乍一看可能会让人困惑,但经过一些练习后,它就会变得不言自明。最后,它只是一个 UNION
,查询略有不同:
WITH RECURSIVE get_ancestor(child,parent,cost) AS (
SELECT r.user_id,r.parent_id,c.cost FROM user_relation r
JOIN product_cost c ON c.user_id = r.user_id
UNION
SELECT g.child,g.parent,c.cost FROM get_ancestor g
JOIN user_relation r ON r.user_id = g.child
JOIN product_cost c ON c.user_id = r.user_id
)
SELECT * FROM get_ancestor;
演示:SQL Fiddle