标题: 读取树型所有下级或所有上级 [打印本页] 作者: 张军勇 时间: 2020-3-14 19:15 标题: 读取树型所有下级或所有上级 在构建中,可能会遇到常常需要根据树型某个节点,读取其所有上级或所有下级的情况。然后绑定到树型部件显示。
在Oracle中,可以用start with ... connect by prior ...来实现。
具体写法是:
查询下级:
select * from sa_dept_dict start with dept_id=2170 connect by prior dept_ID=upper_id order by SORT_ORDER
复制代码
查询上级:
select * from sa_dept_dict start with dept_id=2170 connect by prior upper_id=dept_ID order by SORT_ORDER
复制代码
在SQL SERVER 中就要略复杂一些了。需要用With....AS...语句,这个语句也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片断会
被整个SQL语句所用到。有的时候,是为了让SQL语句的可读性更高些,也有可能是在UNION ALL的不同部分,作为提供数据的部分。
下面我们就用with 结合 union 来查询树型的上级和下级:
查询下级:
with tree as (select * from sa_dept_dict where dept_id=2016 union all
select a.* from sa_dept_dict as a,tree as b where b.dept_id=a.upper_id ) select * from tree order by sort_order
复制代码
查询上级:
with tree as (select * from sa_dept_dict where dept_id=2016 union all
select a.* from sa_dept_dict as a,tree as b where a.dept_id=b.upper_id ) select * from tree order by sort_order