无限层级结构的table1表,Id(主键),ParentId(父级id)查询某个Id的所有下级或所有上级,使用WITH AS,UNION ALL 查询
1、查询Id为1所有的下级
WITH T AS( SELECT * FROM table1 WHERE Id=1 UNION ALL SELECT a.* FROM table1 a INNER JOIN T ON a.ParentId=T.Id ) SELECT * FROM T
2、查询Id为88所有的上级
WITH T AS( SELECT * FROM table1 WHERE Id=88 UNION ALL SELECT a.* FROM table1 a INNER JOIN T ON a.Id=T.ParentId ) SELECT * FROM T
转载于:https://www.cnblogs.com/linJie1930906722/p/9103034.html
原文地址:https://www.cnblogs.com/flms/p/12408619.html
时间: 2024-10-29 06:08:15