postgresql join table on same table until there is no more data to return

postgresql join table on same table untill there is no more data to return

我正在用 pgsql 编写一个函数。我有一个 table A 列 child_of_a。 使用此查询,我可以获得一个 child,但我需要所有这些,但我不知道数据库中有多少。 这个returns只有一行:

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

这returns两行:

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