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

  • 相关阅读:
    BZOJ1862: [Zjoi2006]GameZ游戏排名系统
    BZOJXXXX: [IOI2000]邮局——四边形不等式优化初探
    BZOJ1801: [Ahoi2009]chess 中国象棋
    BZOJ1505: [NOI2004]小H的小屋
    BZOJ1899: [Zjoi2004]Lunch 午餐
    BZOJ1057: [ZJOI2007]棋盘制作
    BZOJ1100: [POI2007]对称轴osi
    BZOJ1123: [POI2008]BLO
    线性规划之单纯形讲解
    BZOJ 3265 志愿者招募加强版(单纯形)
  • 原文地址:https://www.cnblogs.com/Snowolf/p/1978616.html
Copyright © 2011-2022 走看看