斐波纳契数列,又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)
上面是对递归有个小小的了解。下面给出一个具体的例子
这个例子的作用是根据ID值找出该ID对应值下的地区有哪些?
源代码:
---db2递归查询 CREATE TABLE AreaInfo ( ID INTEGER NOT NULL PRIMARY KEY, ParentID INT, NAME VARCHAR(100) ) -- DROP TABLE AreaInfo INSERT INTO AreaInfo VALUES(001,null,'云南省'); INSERT INTO AreaInfo VALUES(002,001,'曲靖市'); INSERT INTO AreaInfo VALUES(003,001,'昭通市'); INSERT INTO AreaInfo VALUES(004,001,'昆明市'); INSERT INTO AreaInfo VALUES(005,002,'陆良县'); INSERT INTO AreaInfo VALUES(006,002,'师宗县'); INSERT INTO AreaInfo VALUES(007,006,'彩云镇'); INSERT INTO AreaInfo VALUES(008,006,'雄壁镇'); INSERT INTO AreaInfo VALUES(009,005,'召夸镇'); INSERT INTO AreaInfo VALUES(010,005,'马街镇'); INSERT INTO AreaInfo VALUES(011,010,'大西村'); INSERT INTO AreaInfo VALUES(012,009,'新庄村'); INSERT INTO AreaInfo VALUES(013,004,'官渡区'); INSERT INTO AreaInfo VALUES(014,013,'官渡镇');
SELECT * FROM AreaInfo
查询结果如下:
查询出ID为2所对应值下的地区:
WITH RPL (ID,ParentID,NAME) AS ( SELECT ID,ParentID,NAME FROM AreaInfo WHERE ID=2 UNION ALL SELECT child.id,child.ParentID,child.name FROM RPL parent,AreaInfo child WHERE parent.id=child.ParentID ) SELECT * FROM RPL
查询出ID为9所对应值下的地区:
WITH PPL (ID,ParentID,NAME) AS ( SELECT ID,ParentID,NAME FROM AreaInfo WHERE ID=9 UNION ALL SELECT child.ID,child.ParentID,child.NAME FROM PPL parent,AreaInfo child WHERE child.ParentID=parent.ID ) SELECT * FROM PPL