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