zoukankan      html  css  js  c++  java
  • SQL递归查询(with cte as)

    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
    

      

    表结构

    Id          Pid         DeptName
    ----------- ----------- --------------------------------------------------
    1           0           总部
    2           1           研发部
    3           1           测试部
    4           1           质量部
    5           2           小组1
    6           2           小组2
    7           3           测试1
    8           3           测试2
    9           5           前端组
    10          5           美工
    

      

    3 原理(摘自网上)

      递归CTE最少包含两个查询(也被称为成员)。第一个查询为定点成员,定点成员只是一个返回有效表的查询,用于递归的基础或定位点。第二个查询被称为递归成员,使该查询称为递归成员的是对CTE名称的递归引用是触发。在逻辑上可以将CTE名称的内部应用理解为前一个查询的结果集。

    递归查询没有显式的递归终止条件,只有当第二个递归查询返回空结果集或是超出了递归次数的最大限制时才停止递归。是指递归次数上限的方法是使用MAXRECURION。

  • 相关阅读:
    Leetcode Substring with Concatenation of All Words
    Leetcode Divide Two Integers
    Leetcode Edit Distance
    Leetcode Longest Palindromic Substring
    Leetcode Longest Substring Without Repeating Characters
    Leetcode 4Sum
    Leetcode 3Sum Closest
    Leetcode 3Sum
    Leetcode Candy
    Leetcode jump Game II
  • 原文地址:https://www.cnblogs.com/LCX/p/4337694.html
Copyright © 2011-2022 走看看