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) 
    
    转自:https://www.cnblogs.com/wgx0428/p/13606375.html#3408585068
  • 相关阅读:
    iOS 开发笔记-获取某个APP素材
    iOS UI基础-15.0 UIWebView
    iOS UI基础-14.0 DatePicker
    iOS UI基础-13.0 数据存储
    iOS UI基础-12.0 Storyboard
    iOS UI基础-11.0 UINavigationController
    iOS UI基础-10.0 QQ聊天布局之键盘及文本使用
    iOS 开发技巧总结
    iOS 设计模式-NSNotificationCenter 通知中心
    iOS UI基础-9.2 UITableView 简单微博列表
  • 原文地址:https://www.cnblogs.com/huangshuqiang/p/15428015.html
Copyright © 2011-2022 走看看