Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何将递归CTE与查找一起使用?_Mysql_Sql_Mariadb - Fatal编程技术网

Mysql 如何将递归CTE与查找一起使用?

Mysql 如何将递归CTE与查找一起使用?,mysql,sql,mariadb,Mysql,Sql,Mariadb,我有一个非常具体的用例,我甚至不确定是否可以使用SQL操作符 我有一个用户表、一个分支表和一个用户到分支视图用户到分支机构视图存在,因为我需要来自用户的id、用户名和分支机构id,以及来自分支机构表的分支机构名和父分支机构id 现在,组织结构图可以分为两层,因此到目前为止,用户的分支机构id是分配给用户的直接分支机构(例如财务部门),但父分支机构id的级别高于该级别(例如X公司)。但例如,如果在财务(如记账)下还有一层,parentBranch\u id将是财务的branch\u id。我需要的

我有一个非常具体的用例,我甚至不确定是否可以使用SQL操作符

我有一个
用户
表、一个
分支
表和一个
用户到分支
视图<代码>用户到分支机构视图存在,因为我需要来自
用户
id
用户名
分支机构id
,以及来自
分支机构
表的
分支机构名
父分支机构id

现在,组织结构图可以分为两层,因此到目前为止,用户的
分支机构id
是分配给用户的直接分支机构(例如财务部门),但
父分支机构id
的级别高于该级别(例如X公司)。但例如,如果在财务(如记账)下还有一层,
parentBranch\u id
将是财务的
branch\u id
。我需要的是始终将结构的最高级别视为
parentBranch\u id
。因此,如果以
分支机构id
记账,我希望将公司X视为
父分支机构id

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


我的想法是:函数必须不断检查
父分支\u id
。如果为空,则将
分支\u id
作为
父分支\u id
传递。如果不为空,则在
分支id
列中查找
父分支id
值-直到它为空。

您将使用递归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;
然后,您可以通过返回到
用户
来使用它:

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;

为了方便您的帮助,请向我们展示一些示例表数据和预期结果-全部为格式化文本(而不是图像)。据我所知,您的分支表是微不足道的父子结构。在递归CTE中从根行开始使用它,并生成表示形式
(ID parentID rootID)
(或
(ID fullPath)
)。然后连接其他表并检索所需的数据。