• 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

  • 相关阅读:
    Linux下使用select延时
    update不能直接使用select的返回结果
    C++类模板声明与定义为何不能分开
    MySQL开启日志记录执行过的SQL语句
    如何使用FastCGI处理自定义HTTP头
    MongoDB添加认证
    Ubuntu16.04安装MongoDB
    nginx: [emerg] getpwnam(“www”) failed
    C++ 智能指针(一)
    协同过滤
  • 原文地址:https://www.cnblogs.com/Snowolf/p/1978616.html
Copyright © 2020-2023  润新知