以图中的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 = 2
union
即可
查询结果:
2. 获取所有父节点sql:文章来源:https://www.toymoban.com/news/detail-612138.html
SELECT t2.id
FROM ( 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://www.toymoban.com/news/detail-612138.html
到了这里,关于以mysql为例,通过sql查找所有父节点和所有子节点的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!