递归查询以从给定的ID中检索所有孩子
我正在从Oracle迁移到Postgres,但我不知道该如何进行递归查询
是一个示例数据集:
ID | id_parent | 名称 |
---|---|---|
1 | 0 | AA |
2 | 0 | AA |
3 1 | 3 | AA |
4 | AA 4 3 | AA |
5 | 3 | AA 6 AA |
6 | 2 AA 7 6 | AA |
6 | AA | AA |
对于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:
id | id_parent | name |
---|---|---|
1 | 0 | aa |
2 | 0 | aa |
3 | 1 | aa |
4 | 3 | aa |
5 | 3 | aa |
6 | 2 | aa |
7 | 6 | aa |
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无需使用子问题。您只需要仅修复递归查询,为 -
There is no need of using sub-query. You just need to fix your recursive query only as -
Demo.