【问题标题】:Migrate Oracle CONNECT BY to postgresql 10将 Oracle CONNECT BY 迁移到 postgresql 10
【发布时间】:2020-02-15 04:00:53
【问题描述】:

我有这个 SQL:

SELECT count(*) as ct
          FROM classifications cls
WHERE
   cls.classification_id = :classification_id
START WITH cls.classification_id = :root_classification_id
CONNECT BY NOCYCLE PRIOR cls.classification_id = cls.parent_id

并且需要将其迁移到 postgresql 10。

我已经安装了扩展 tablefunc 并尝试使用 connectedby。这是我的尝试:

SELECT count(*) as ct
          FROM classifications cls
WHERE
   cls.classification_id = :classification_id

union
                  SELECT count(classification_id) FROM connectby('classifications','classification_id','parent_id',:root_classification_id,5)
                  as t(classification_id varchar, parent_id varchar,level int) 

问题是联合是错误的方式,因为这样你会得到 2 个计数结果。

【问题讨论】:

    标签: sql postgresql database-migration recursive-query


    【解决方案1】:

    无需使用 tablefunc 扩展。这可以使用recursive CTE 轻松完成

    with recursive tree as (
    
      select cls.classification_id, cls.parent_id 
      from classifications cls
      where cls.classification_id = :root_classification_id
    
      union all
    
      select child.classification_id, child.parent_id
      from classifications child
         join tree parent on child.parent_id = parent.classification_id
    )
    select count(*)
    from tree;
    

    CTE 中的第一个查询与 Oracle 的 start with 中的 start with 部分匹配。第二个查询中返回 CTE 的 JOIN 与 Oracle 查询中的 connect by 部分匹配。

    【讨论】:

    • 值得注意的是,这适用于大多数 RDBMS,几乎没有修改。我想知道 ltree 是否也是一个不错的选择?这是一个额外的模块,但会带来更好的性能。
    • @PanagiotisKanavos:我从未使用过 ltree 扩展,但递归查询在 Postgres 中非常有效(我已将它们与包含数千行的树一起使用,这些树包含数百万行的表,没有任何问题 -假定适当的索引)
    • 不如对索引的单个范围查询有效。 LTree 就像 SQL Server 的 hierarchyid - 一种二进制路径编码,大致类似于 ID1\ID2 等,这意味着搜索子项本质上是类似于 like 'ID1\% 的范围查询。寻找父母,只是寻找那些IDs。嵌套集也很快,但更难维护,而且无论如何都需要手动实现
    • @PanagiotisKanavos:如果 Oracle 中的当前结构表现得足够好,我相信这个查询在 Postgres 中也足够好。
    猜你喜欢
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2016-08-22
    • 2020-10-19
    • 2012-04-05
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    相关资源
    最近更新 更多