MySQL 递归遍历查询

1. 按照层级查询部门信息

        (1)部门表 department,包含id、parent_id两个字段

        (2)部门变量名: @departmentId

        (3)查询字符串函数: find_in_set(str, filterStr)

2. SQL

select

t1.department_id,

t1.parent_id,

case when find_in_set(parent_id, @depID) > 0 

then @depID := concat(@depID, ',', department_id)   

else 0 end as ischild

from

( select department_id, parent_id from department t order by parent_id, department_id ) t1,

( select @depID := {param}  ) t2

3. 查询字段

    ischild = 0 时,为顶级部门,其他为包含子部门Id

你可能感兴趣的:(MySQL 递归遍历查询)