1 select dept_id from ( 2 select t1.dept_id,t1.parent_id, 3 if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', dept_id), 0) as ischild 4 from ( 5 select dept_id,parent_id from sys_dept t where t.del_flag = '0' order by parent_id, dept_id 6 ) t1, 7 (select @pids := 要查詢的節點id) t2 8 ) t3 where ischild != 0;
解釋:
@pids := 要查詢的節點id 變量定義。
concat() 拼接字符串
find_in_set(parent_id, @pids) parent_id 字符串是否在@pids字符串中。
select find_in_set('2','1,2');返回2
select find_in_set('6','1');返回0
if(express1,express2,express3)條件語句,if語句類似三目運算符,當exprss1成立時,執行express2,否則執行express3;
拆分語句:select dept_id,parent_id from sys_dept t where t.del_flag = '0' order by parent_id, dept_id

select @pids := 要查詢的節點id
select * from (
select dept_id,parent_id from sys_dept t where t.del_flag = '0' order by parent_id, dept_id
) t1,
(select @pids :=4) t2
select t1.dept_id,t1.parent_id,t2.*,
if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', dept_id), 0) as ischild
from (
select dept_id,parent_id from sys_dept t where t.del_flag = '0' order by parent_id, dept_id
) t1,
(select @pids := 4) t2
select dept_id from (
select t1.dept_id,t1.parent_id,t2.*,
if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', dept_id), 0) as ischild
from (
select dept_id,parent_id from sys_dept t where t.del_flag = '0' order by parent_id, dept_id
) t1,
(select @pids := 4) t2
) t3 where ischild != 0;