【问题标题】:How to use recursive CTE with LOOKUP?如何在 LOOKUP 中使用递归 CTE?
【发布时间】:2021-04-16 09:40:55
【问题描述】:

我有一个非常具体的用例,我什至不确定是否可以使用 SQL 运算符。

我有一个users 表、一个branches 表和一个users_to_branches 视图。 users_to_branches 视图存在,因为我需要来自usersidusernamebranch_id,以及来自branch_name(不存在于users)和来自branches 表的parentBranch_id

现在组织结构图可以分为几层,所以现在用户的branch_id 是用户被分配到的直接分支(例如财务),但parentBranch_id 是高于该水平(例如 X 公司)。但例如,如果还有一层,在财务(例如簿记)下,parentBranch_id 将是财务的branch_id。我需要的是始终将结构的最高级别视为parentBranch_id。因此,在簿记为branch_id 的情况下,我希望将X 公司视为parentBranch_id

我在看什么样的逻辑?我读过它必须涉及递归 CTE,但是如何实现 LOOKUP 函数并用它传递值?

我的想法:该功能必须不断检查parentBranch_id。如果为 NULL,则将 branch_id 传递为 parentBranch_id。 IF NOT NULL 然后在 branch_id 列中查找 parentBranch_id 值 - 直到它为 NULL。

【问题讨论】:

  • 轻松为您提供帮助,向我们展示一些示例表数据和预期结果 - 全部为格式化文本(不是图像)。minimal reproducible example
  • 据我了解,您的 Branches 表是微不足道的父子结构。在从根行开始的递归 CTE 中以常用方式使用它并生成表示 (ID-parentID-rootID)(或 (ID-fullPath))。然后加入另一个表并检索所需的数据。

标签: mysql sql mariadb


【解决方案1】:

您将使用递归 CTE 获得每个分支 id 的最终父分支。像这样的:

with recursive cte as (
      select b.branch_id as ultimate_parent_branch_id, b.branch_id as branch_id
      from branches b
      where parent_branch_id is null
      union all
      select cte.ultimate_parent_branch_id, b.branch_id
      from cte join
           branches b
           on b.parent_branch_id = cte.branch_id           
     )
select *
from cte;

然后你就可以通过加入users来使用它:

with recursive cte as (
      select b.branch_id as ultimate_parent_branch_id, b.branch_id as branch_id
      from branches b
      where parent_branch_id is null
      union all
      select cte.ultimate_parent_branch_id, b.branch_id
      from cte join
           branches b
           on b.parent_branch_id = cte.branch_id           
     )
select *
from users u join
     user_branches ub
     on u.user_id = ub.user_id join
     cte
     on cte.branch_id = ub.branch_id;

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2019-09-30
    • 2019-03-10
    • 2018-12-13
    相关资源
    最近更新 更多