mysql数据库递归查询实现

部门表里有fid和父级的fparentid(FID的子集),当在部门审批角色(部门fid(没有包含全部部门),角色fid)没有找到部门对应的审批人时,则用父级取找审批角色;父级没有找到,则用父级的父级,直到返回角色值,或者是整个组织树遍历,也没有角色返回,那么返回null。要求不使用存储过程和游标。

你这是强行在数据层实现业务功能啊,你查出所有部门信息根据id分组,代码里面一个个去get出来做判断不是更好一点吗

with recursive tempTable as(
            select fid,fparentid,'1' deplevel 
            from 部门表
            where fid =部门fid
            union all
            select t.fid,t.fparentid,(deplevel+1)deplevel 
            from 部门表 t inner join tempTable t1
            on t.fid = t1.fparentid
        )select
                审批人信息
        from tempTable a
        inner join 部门审批角色表 b on a.fid=b.fid
        #这里用了inner join ,视情况可以再加where 条件
        order by deplevel LIMIT 1

若有帮助,请采纳~