递归查询以从给定的ID中检索所有孩子

发布于 2025-02-07 02:54:07 字数 2175 浏览 0 评论 0原文

我正在从Oracle迁移到Postgres,但我不知道该如何进行递归查询

是一个示例数据集:

IDid_parent名称
10AA
20AA
3 13AA
4AA 4 3AA
53AA 6 AA
62 AA 7 6AA
6AAAA

对于ID = 3,我想获得

ID
3
4
5

for ID = 1

ID
1
3
4
5,

但我都有所有,但我不知道如何通过ID过滤:

SELECT id FROM (  
        with recursive cat as ( 
            select * from table
             union all 
            select  table.* 
            from table  
            join cat on cat.id_parent = table.id
        ) 
        select  * from cat order by id 
    )
    as listado where id != '0'  group by id

I am migrating from oracle to postgres and I don't know how to make a recursive query

Here is an example data set:

idid_parentname
10aa
20aa
31aa
43aa
53aa
62aa
76aa

For id = 3, I want to get

id
3
4
5

for id =1

id
1
3
4
5

with this I have all but I don't know how to filter by id:

SELECT id FROM (  
        with recursive cat as ( 
            select * from table
             union all 
            select  table.* 
            from table  
            join cat on cat.id_parent = table.id
        ) 
        select  * from cat order by id 
    )
    as listado where id != '0'  group by id

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娇妻 2025-02-14 02:54:07

无需使用子问题。您只需要仅修复递归查询,为 -

WITH RECURSIVE cat (id, id_parent) as 
    ( 
     SELECT id, id_parent
       FROM table
      WHERE id = 1
      UNION ALL
     SELECT d.id, d.id_parent
       FROM table d
       JOIN cat ON cat.id = d.id_parent
    ) 
SELECT id 
  FROM cat 
 ORDER BY id;

There is no need of using sub-query. You just need to fix your recursive query only as -

WITH RECURSIVE cat (id, id_parent) as 
    ( 
     SELECT id, id_parent
       FROM table
      WHERE id = 1
      UNION ALL
     SELECT d.id, d.id_parent
       FROM table d
       JOIN cat ON cat.id = d.id_parent
    ) 
SELECT id 
  FROM cat 
 ORDER BY id;

Demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文