zoukankan      html  css  js  c++  java
  • SQL 树形结构递归查询

    常规树形表结构

    方式一:WITH AS

    WITH AS短语,也叫做子查询部分(subquery factoring),定义一个sql 片段,改sql 片段会被整个sql语句用到。其中最实用的功能就是数据的递归,递归的原理:递归包括至少两个查询,一个查询作为递归的基点也就是起点,另一个查询作为递归的成员。

    查询某个节点级所属子节点

    with temp as
    (
    	select * from Base_Module where FullName='陕西省'
    	union all
    	select c.* from Base_Module as c,temp t where c.ParentId=t.Id
    )
    select * from temp
    

    结果

    注意点:

    语句1隐式的内连接,没有INNER JOIN,形成的中间表为两个表的笛卡尔积。
    select c.* from Base_Module as c,temp t where c.ParentId=t.Id

    语句2显示的内连接,一般称为内连接,有INNER JOIN,形成的中间表为两个表经过ON条件过滤后的笛卡尔积。
    select b.* from a inner join Base_Module b on a.ParentId=b.Id

    查询某个节点的所有上层机构

    with a as
    (
    	select * from Base_Module where FullName='韩城市'
    	union all
    	select b.* from a, Base_Module b where a.ParentId=b.Id
    )
    select * from a where a.FullName<>'韩城市'
    

    结果

    删除节点及包含的所有子节点

    with temp as
    (
    	select Id,ParentId from Base_Module where FullName='陕西省'
    	union all
    	select a.Id,a.ParentId from Base_Module as a inner join temp b on a.ParentId=b.Id
    ) delete from Base_Module where Id in (select Id from temp)  
    
  • 相关阅读:
    CleanWebpackPlugin
    webpack
    kubeadm部署k8s
    leetcode 148 链表排序的归并排序和插入排序
    102 二叉树层序遍历(一下出一层的广搜和DFS)
    139 单词拆分 dp
    48 旋转图像 水平翻转然后主对角线翻转即可实现顺时针旋转90°
    31下一个排列
    最长连续序列
    每日总结22——SQL语句(保持现有内容在后面增加内容)
  • 原文地址:https://www.cnblogs.com/wgx0428/p/13606375.html
Copyright © 2011-2022 走看看