实验环境:
db2版本:DB2 v10.1.0.872
db2客户端:Aqua Data Studio 19.0 - 64bit
CREATE TABLE LEI.AREA (
CODE VARCHAR(100) NOT NULL,
NAME VARCHAR(100),
PARENTCODE VARCHAR(100),
LEVEL INTEGER,
PRIMARY KEY(CODE)
)
GO
COMMENT ON COLUMN LEI.AREA.CODE IS '行政区划代码'
GO
COMMENT ON COLUMN LEI.AREA.NAME IS '行政区划名称'
GO
COMMENT ON COLUMN LEI.AREA.PARENTCODE IS '父级行政区划代码'
GO
COMMENT ON COLUMN LEI.AREA.LEVEL IS '等级'
GO
insert into AREA
select '110000' as Code, '北京市' Name, 'Root' parentCode, 1 level FROM SYSIBM.SYSDUMMY1 union all
select '110101' , '东城区' , '110000', 2 FROM SYSIBM.SYSDUMMY1 union all
select '110101001' , '东华门街道', '110101', 3 FROM SYSIBM.SYSDUMMY1 union all
select '110101002' , '景山街道' , '110101', 3 FROM SYSIBM.SYSDUMMY1 union all
select '110102' , '西城区', '110000', 2 FROM SYSIBM.SYSDUMMY1 union all
select '110102001' , '西长安街街道', '110108', 3 FROM SYSIBM.SYSDUMMY1 union all
select '110102003' , '新街口街道', '110108', 3 FROM SYSIBM.SYSDUMMY1 union all
select '110108' , '海淀区' , '110000', 2 FROM SYSIBM.SYSDUMMY1 union all
select '110108001' , '万寿路街道', '110108', 3 FROM SYSIBM.SYSDUMMY1 union all
select '110108002' , '永定路街道', '110108', 3 FROM SYSIBM.SYSDUMMY1
查询结果如下:
select * from area order by level
2.1、向上递归(根据子节点查其至父节点的路径,比如,万寿路街道,其向上递归路径为万寿路街道-海淀区-北京市),寻祖溯源
with temp(code,name,level,parentcode) as
(
select code,name,level,parentcode from AREA where name='万寿路街道'
union all
select area.code,area.name,area.level,area.parentcode from area,temp where area.code=temp.parentcode
)
select * from temp order by level
2.2、向下递归(根据父节点查询其包含的所有孩子节点),比如北京包含海淀区,海淀区又包含永定路街道、万寿路街道…
with temp(code,name,level,parentcode) as
(
select code,name,level,parentcode from AREA where name='北京市'
union all
select area.code,area.name,area.level,area.parentcode from area,temp where area.parentcode=temp.code
)
select * from temp order by level
总结:决定是向上还是向下的关键就是递归拼接时的父子关联关系;
temp.parentcode=area.code为向上递归 :拼接时(就是union all时),根据存储的parentcode去找其对应的父节点,即去找父项;
temp.code=area.parentcode为向下递归 :拼接时(就是union all时),根据节点自身的code去找parentcode为它的子节点,即去找子项;