zoukankan      html  css  js  c++  java
  • sql 递归查询所有的下级

    --> 生成测试数据表: [tb]

    IF OBJECT_ID('[Users]'IS NOT NULL
        DROP TABLE [Users]
    GO
    CREATE TABLE [Users] ([userid] [int],[username] [nvarchar](10),[parentUserId] [int],[parentUserName] [nvarchar](10))
    INSERT INTO [Users]
    SELECT '1','admin','0',NULL UNION ALL
    SELECT '2','aaaaa','1','admin' UNION ALL
    SELECT '3','bbbbb','2','aaaaa' UNION ALL
    SELECT '4','ddddd','3','bbbbb'
    -->SQL查询如下:
    ;with as
    (
      select *,level=1 from Users where [parentUserId]=0
      union all
      select a.*,level+1 from Users a join t b on a.parentUserId=b.userid
    )
    select from where [parentUserId]<>0
    /*
    userid      username   parentUserId parentUserName level
    ----------- ---------- ------------ -------------- -----------
    2           aaaaa      1            admin          2
    3           bbbbb      2            aaaaa          3
    4           ddddd      3            bbbbb          4
      
    (3 行受影响)
    */
  • 相关阅读:
    LeetCode-Cycle Detection,Find the Duplicate Number
    LeetCode-Symmetric Tree
    剑指offer-打印链表倒数第k个结点
    Http协议中Get和Post的区别
    ORDER BY 语句
    AND 和 OR 运算符
    WHERE 子句
    SQL SELECT DISTINCT 语句
    SQL SELECT 语句
    SQL DML 和 DDL
  • 原文地址:https://www.cnblogs.com/soundcode/p/7073916.html
Copyright © 2011-2022 走看看