以图中的dept表为例:
id:主键
parent_id:父id
name:名称
1. 获取所有子节点sql:
select id from dept where id = 2 union select t.id from (select * from dept where parent_id is not null) t, (select @pid := 2) pd where FIND_IN_SET(parent_id,@pid) > 0 and @pid := CONCAT(@pid,',',id)
此sql查询id=2的所有子节点id,并包括当前id=2的节点,如果不想包括当前节点,去掉
select id from dept where id = 2union
即可
查询结果:
2. 获取所有父节点sql:
SELECT t2.idFROM ( SELECT @r AS _id, (SELECT @r := parent_id FROM dept WHERE id = _id) AS parent_id, @l := @l + 1 AS lvl FROM (SELECT @r := 3, @l := 0) vars, dept WHERE @r != 0) t1 JOIN dept t2 ON t1._id = t2.id ORDER BY t1.lvl DESC
此sql查询id=3的所有父节点sql,
查询结果:
来源地址:https://blog.csdn.net/scorpio_meng/article/details/131209973