zoukankan      html  css  js  c++  java
  • SQL语句递归查找

    通过sql语句递归查找所有下级或上级用户

    1.MS Sql

    with cte as
    (
       
    select Id,Pid,DeptName,0 as lvl from Department
       
    where Id = 2
       
    union all
       
    select d.Id,d.Pid,d.DeptName,lvl+1 from cte c inner join Department d
       
    on c.Id = d.Pid
    )
    select * from cte

    2.Oracle

     一、建表

      CREATE TABLE USERS.TBL_TEST

      (

      ID    NUMBER,

      NAME  VARCHAR2(100 BYTE),

      PID   NUMBER                                  DEFAULT 0

      )

      INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('1','10','0');

      INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('2','11','1'

      INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('3','20','0');

      INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('4','12','1');

      INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('5','121','2');

      二、格式

      Select * from …. Where [结果过滤条件语句]

      Start with  [and起始条件过滤语句]

      Connect by prior [and中间记录过滤条件语句]

      三、查找所有下级

      select * from tbl_test start with id=1 connect by prior id=pid

      注意:此sql能查找id=1的数据的所有下级,写sql语句时要注意,因为是从id开始查找下级,所以connect by prior 子句的条件是id=pid

      四、查找所有上级

      select * from tbl_test start with id=5 connect by prior pid=id

      因为是从id开始查找上级,所以connect by prior 子句的条件是pid=d

  • 相关阅读:
    flutter 网络请求以及数据处理
    flutter 布局 Expanded Stack Positioned
    异步|同步&阻塞|非阻塞
    Spring AOP 由浅入深
    Elasticsearch初探
    dubbo工作原理
    BeanFactory vs ApplicationContext
    Spring container vs SpringMVC container(webmvc container)
    Spring @Service生成bean名称的规则
    MySQL绿色版安装(mysql-5.7.12-win32)
  • 原文地址:https://www.cnblogs.com/Snowolf/p/1978616.html
Copyright © 2011-2022 走看看