【问题标题】:Converting oracle's "connect by prior" to mariaDB将 oracle 的“之前连接”转换为 mariaDB
【发布时间】:2020-05-31 15:25:19
【问题描述】:

我必须从 Oracle 迁移到 MariaDB 10.3.21。 花了一整天的时间。 我对 oracle 使用“start with”和“connect by prior”和“order brother by”进行了查询。

        select * from (select * from table_name ";
        where num = 1045 ) ";
        start with parentid = 0 ";
        connect by prior id = parentid ";
        order siblings by parentid asc ";

但 MariaDB 不起作用。 使用递归但并不顺利。 任何人都可以分享一个好主意吗?

这是原始表格。

------------------------------------
num     id   parentid       data1
------------------------------------
1045    11      4          zzzzz
1048    3       0          a3
1048    1       0          a1
1050    21      17         eeeee
1048    2       0          a2
1048    4       1          a1-1
1048    5       4          a1-1-1
1048    6       3          a3-1
------------------------------------

我不会用 MariaDB 得到同样的结果。

------------------------------------
num     id   parentid       data1
------------------------------------
1048    1       0          a1
1048    4       1          a1-1
1048    5       4          a1-1-1
1048    2       0          a2
1048    3       0          a3
1048    6       3          a3-1
-------------------------------------

有什么好主意吗? 永远感谢。

【问题讨论】:

    标签: mysql oracle mariadb


    【解决方案1】:

    我不使用 MariaDB,但正如我在 documentation 中看到的那样,它支持递归公用表表达式。所以你可以这样写:

    with recursive rcte as (
      select num, id, parentid, data1 from table_name where parentid = 0 and num = 1048
      union all 
      select t.num, t.id, t.parentid, t.data1 
        from table_name t join rcte on t.parentid = rcte.id and t.num = rcte.num)
    select * from rcte
    

    MariaDB dbfiddle

    Oracle dbfiddle

    如果您想重现 Oracle order by siblings,您需要创建 层次结构列 并将其用于排序:

    with recursive rcte as (
      select cast(id as char) AS hierarchy, num, id, parentid, data1 
        from table_name where parentid = 0 and num = 1048
      union all 
      select concat(rcte.hierarchy, '-', t.id), t.num, t.id, t.parentid, t.data1 
        from table_name t join rcte on t.parentid = rcte.id and t.num = rcte.num)
    select * 
       from rcte
       order by hierarchy
    

    【讨论】:

      【解决方案2】:

      看起来公用表表达式是解决这个问题的新方法:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-26
        • 1970-01-01
        • 2017-04-08
        • 1970-01-01
        • 1970-01-01
        • 2014-07-08
        • 2018-06-23
        相关资源
        最近更新 更多