mysql实现根据传入的部门id查询此部门下所有的子部门和子部门的子部门

要注意的一点,一定要按照部门层级的顺序从一级部门开始遍历查询

SELECT
            dept_id
            FROM
            (
            SELECT
            t1.dept_id,t1.dept_name,t1.dept_parentid,
            IF
            ( find_in_set( dept_parentid, @pids ) > 0, @pids := concat( @pids, ',', dept_id ), -1 ) AS ischild
            FROM
            ( 
            -- 这里后面需要加上order by  dept_level 我这没加是应为自然排序就是从一级部门依次往下的
            SELECT dept_id, dept_parentid,dept_name FROM org_department t 
            ) t1,
            ( SELECT @pids := #{deptId} ) t2
            ) t3
            WHERE
            ischild != -1 
            -- 这一步操作是为了查当前部门
            or dept_id = #{deptId}

#{deptId} 替换成自己要传入的部门id的值就可以了,拿掉or dept_id = #{deptId} 查询的就是当前部门下的所有子部门,加上就是查询当前部门以及所有子部门可以根据自己的需要改造一下

第二种写法:


								SELECT
	        dept_id,dept_name
        FROM
	        (
	        SELECT
		        @ids AS _ids,
						FIND_IN_SET( dept_parentid, @ids ),
		        ( SELECT @ids := GROUP_CONCAT( dept_id ) FROM org_department WHERE FIND_IN_SET( dept_parentid, @ids ) ) AS cids,
		        @l := @l + 1 AS LEVEL
            FROM
                org_department,
                ( SELECT @ids := #{deptId}, @l := 0 ) b
            WHERE
                @ids IS NOT NULL
            ) id,
            org_department DATA
        WHERE
            FIND_IN_SET( DATA.dept_id, ID._ids )
        ORDER BY
            LEVEL,
            dept_id

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值