要注意的一点,一定要按照部门层级的顺序从一级部门开始遍历查询
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