繁体   English   中英

用于查找匹配的递归 SQL 查询

[英]Recursive SQL query for finding matches

我有 5 个 SQL 表,其中包含以下列:

tbl_department:

department_id, parent_id


tbl_employee

employee_id, department_id


tbl_department_manager

department_id, employee_manager_id


tbl_request_regular_employee

request_id, employee_id


tbl_request_special_employee

request_id, employee_id

作为输入数据,我有employee_idrequest_id

我需要弄清楚员工是否有权访问请求(他是否是经理)

我们不能在这里使用 ORM 因为应用程序的响应性是我们的首要任务,并且脚本可能会被大量调用。

这是我要实现的逻辑:

  1. 首先根据employee_id查询tbl_department_manager ,判断当前员工是否为经理(也可以是少数部门的经理)。 如果是,我们得到一个department_id列表(如果没有找到,就返回 false)
  2. 如果我们在tbl_department_manager中至少有一个 id,我们会根据request_id查询tbl_request_regular_employee AND tbl_request_special_employee并从两个表中获取employee_id (它们是相同的)
  3. 根据上面收集的employee_id ,我们查询tbl_employee以获取该员工所属的department_id的唯一列表。
  4. 最后有一个来自 p.3 的唯一department_id ID 列表,我们可以将其与我们在 p.1 中获得的一个(一个)进行比较。
  5. 然而,问题在于,在tbl_department中可能有部门继承自我们从 p.1 获得的一个(一个)(因此我们可能需要根据parent_id递归地找到它,直到我们找到至少一个匹配一个元素从第 1 页开始)。 如果 p.1 中的一个元素与 p.3 中的一个元素之间至少有一个匹配项,则返回 true。 所以需要递归查找。

有人可以提供一个线索如何在 MSSQL 中实现它吗? 任何帮助将不胜感激。

declare @employee_id int, @request_id int;

with reqEmployees as (
    select regular_employee_id as employee_id
    from tbl_request_regular_employee
    where request_id = @request_id
  union all      --concatenate the two tables
    select special_employee_id
    from tbl_request_special_employee
    where request_id = @request_id
),
cte as (
    select e.department_id, null as parent_id
    from reqEmployees r
    join tbl_employee e  on e.employee_id = r.employee_id -- get these employees' departments
    union all
    select d.department_id, d.parent_id
    from cte              -- recurse the cte
    join tbl_department d on d.department_id = cte.parent_id   -- and get parent departments
)
-- we only want to know if there is any manager row, so exists is enough
select case when exists (select 1
    from cte   --join on managers
    join tbl_department_manager dm on dm.department_id = cte.department_id
    where dm.employee_manager_id = @employee_id)
  then 1 else 0 end;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM