【问题标题】:Recursive query in mysql_mysql中的递归查询
【发布时间】:2020-07-29 15:16:32
【问题描述】:

我在 organization_table 中有一个组织层次结构。 在这张表中,我有类似的数据,

--------------------------------------------------------------
organization_id | organisation_type | organization_parent_id |    
--------------------------------------------------------------  Sample
101             |   Primary         | 101                    |   101
102             |   Secondary       | 101                    |    |
103             |   Secondary       | 102                    |   102
104             |   Primary         | 104                    |    |
105             |   Secondary       | 104                    |   103
106             |   Secondary       | 105                    |

这里 101 是 101,102 的主要父代,而 103 与 104 是 104、105 和 106 的主要父代相同。 因此,通过查询,我需要找到 record_id 103 和 106 的 Primary parent。

我在递归查询执行方面很弱,所以请帮我找到合适的方法。

提前致谢。!

【问题讨论】:

标签: mysql sql database


【解决方案1】:

如果我理解正确,递归 CTE 看起来像:

with recursive cte as (
      select organization_id, organization_parent_id, 1 as lev
      from organization_table ot
      where organization_id in (103, 106)
      union all
      select cte.organization_id, ot.organization_parent_id, lev + 1
      from cte join
           organization_table ot
           on ot.organization_id = cte.organization_parent_id
      where organization_id in (103, 106)
    )
select cte.*
from (select cte.*,
             row_number() over (partition by organization_id order by lev desc) as seqnum
      from cte
     ) cte
where seqnum = 1;

【讨论】:

    【解决方案2】:
    WITH RECURSIVE
    cte AS ( SELECT organization_id, organization_parent_id
             FROM organization_table
             WHERE organization_id IN (103, 106)
           UNION ALL
             SELECT ot.organization_id, ot.organization_parent_id
             FROM cte
             JOIN organization_table ot ON ot.organization_id = cte.organization_parent_id
             WHERE cte.organization_id != cte.organization_parent_id
           )
    SELECT *
    FROM cte
    WHERE organization_id = organization_parent_id;
    

    fiddle

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 2014-09-11
      • 2015-05-05
      • 1970-01-01
      • 2019-05-14
      相关资源
      最近更新 更多