gpt4 book ai didi

postgresql 在同一张表上连接表,直到没有更多数据可返回

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

我正在用 pgsql 编写一个函数。我有一个包含 child_of_a 列的表 A。使用此查询,我可以得到一个 child ,但我需要所有 child ,但我不知道数据库中有多少 child 。这只返回一行:

SELECT * FROM A a 
INNER JOIN A a2
ON a2.id=a.child_of_a

这将返回两行:

SELECT * FROM A a 
INNER JOIN A a2
ON a2.id=a.child_of_a
INNER JOIN A a3
ON a3.id=a2.child_of_a

有没有办法在postgres中解决这个问题,不用加入100次?

最佳答案

你正在寻找一个递归查询:

with tree as (
select *
from a
where id = ... --- this is your starting point

union all

select c.*
from a as c
join tree as p on c.child_of_a = p.id
)
select *
from tree;

有关详细信息,请参阅手册:https://www.postgresql.org/docs/current/static/queries-with.html

关于postgresql 在同一张表上连接表,直到没有更多数据可返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592906/

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