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

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

posted @ 2018-11-25 16:12  冰封的心  阅读(939)  评论(0编辑  收藏  举报