以图中的dept表为例: id:主键 parent_id:父id name:名称 1. 获取所有子节点sql: select id from dept where id = 2 union selec
以图中的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
--结束END--
本文标题: 以mysql为例,通过sql查找所有父节点和所有子节点
本文链接: https://lsjlt.com/news/371586.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0