sql - postgres 中的 connect_by_root 等价物

标签 sql oracle postgresql

我如何在 postgres 中隐藏 oracle 的 connect_by_root 查询。 例如:这是一个 oracle 查询。

select fg_id, connect_by_root fg_id as fg_classifier_id
from fg
start with parent_fg_id is null
connect by prior fg_id = parent_fg_id 

最佳答案

您将使用一个递归公用表表达式,它简单地“承载”递归级别的根:

with recursive fg_tree as (
  select fg_id, 
         fg_id as fg_clasifier_id -- <<< this is the "root" 
  from fg
  where parent_fg_id is null -- <<< this is the "start with" part
  union all
  select c.fg_id, 
         p.fg_clasifier_id
  from fg c 
    join fg_tree p on p.fg_id = c.parent_fg_id -- <<< this is the "connect by" part
) 
select *
from fg_tree;

手册中有关递归公用表表达式的更多详细信息:http://www.postgresql.org/docs/current/static/queries-with.html

关于sql - postgres 中的 connect_by_root 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22296248/

相关文章:

Sql表设计-从唯一键与业务键中选择主键

database - 错误: ORA-12560: TNS:protocol adapter error

python - 考虑语言环境对元组列表进行排序(瑞典顺序)

PostgreSQL : comparing two sets of results does not work

mysql - 需要 SQL 帮助 - 跟踪已发送的电子邮件

sql - 表别名如何影响性能?

java - 什么以及为什么是 Java 6 和 Java 7?

json - Entity Framework 电动工具和 PostgreSQL JSON 数据类型

mysql - 从多个表中选择相同的数据并忽略其他列

oracle - 如何在oracle上添加主键约束?