码迷,mamicode.com
首页 > 数据库 > 详细

MYSQL根据节点向上和向下查询所有节点

时间:2018-11-25 17:47:07      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:nbsp   select   mysql   mysq   rom   根据   unit   level   节点   

WITH cte
AS
(
SELECT * ,UnitID AS level FROM UnitTable WHERE UnitID=2
UNION ALL
SELECT g.*,level+1 FROM UnitTable g INNER JOIN cte
ON g.FatherID=cte.UnitID
)
SELECT * FROM cte

 

WITH cte
AS
(
SELECT *,0 as level FROM UnitTable WHERE FatherID=0
UNION ALL
SELECT g.*,level+1 FROM UnitTable g INNER JOIN cte
ON g.FatherID=cte.UnitID

)
SELECT * FROM cte


WITH cte
AS
(
SELECT * ,UnitID AS level FROM UnitTable WHERE UnitID=2
UNION ALL
SELECT g.*,g.UnitID AS level FROM UnitTable g INNER JOIN cte ON g.UnitId=cte.FatherID
)
SELECT * FROM cte

MYSQL根据节点向上和向下查询所有节点

标签:nbsp   select   mysql   mysq   rom   根据   unit   level   节点   

原文地址:https://www.cnblogs.com/yibinboy/p/10015985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!