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)  
    
  • 相关阅读:
    微软 软件的 一组堆成快捷键
    C#事件 的讲解
    软件缺陷分析的几种方法
    一个长三角人对深圳的看法 (转)
    一次LoadRunner的CPC考试经历
    测试是一门武功
    ORACLE的性能测试经验总结
    深圳测试协会第九次论坛在深圳举行
    10月28日参加了IBM的产品推介会
    什么是web安全性测试?
  • 原文地址:https://www.cnblogs.com/wgx0428/p/13606375.html
Copyright © 2011-2022 走看看