Sql递归原理
递归最少包括两个查询(也被称为成员)。第一个查询为定点成员,定点成员只是一个返回有效表的查询,用于递归的基础或定位点。
第二个查询被称为递归成员,使该查询成为递归成员的是对递归引用时触发(递归表.id与该表的pid)。在逻辑上,可以将其理解为是前一个查询语句的子集。
递归查询没有显式的递归终止条件,只有当第二个递归查询返回空结果集或是超出了递归次数的最大限制时才停止递归。递归次数上限的方法是使用MAXRECURION。
实践是检验真理的唯一标准
1.建立数据库
2.录入数据
设Id是唯一标识,FatherID是指向父类的ID,Data包含一些数据。
基本模板
with Re as(select * from Test where id = 1
union all select Test.* from Re, Test where Re.Id = Test.FatherID)
select * from Re
union all select Test.* from Re, Test where Re.Id = Test.FatherID)
select * from Re
Re是递归体,后面的Select是用来显示结果的,可以接条件语句。
3.查询Id为“2”的子节点
with Re as(select * from Test where id = 2
union all select Test.* from Re, Test where Re.Id = Test.FatherID)
select * from Re where Id <> 2
union all select Test.* from Re, Test where Re.Id = Test.FatherID)
select * from Re where Id <> 2
4.查询Id为“7”的父节点
with Re as(select * from Test where id = 7
union all select Test.* from Re, Test where Re.FatherID = Test.Id)
select * from Re where Id <> 7
union all select Test.* from Re, Test where Re.FatherID = Test.Id)
select * from Re where Id <> 7
5.后面的查询语句可以换成其他功能的语句,我就不实验了。