六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 80|回复: 0

db2树形结构sql问题(转)

[复制链接]

升级  86%

11

主题

11

主题

11

主题

童生

Rank: 1

积分
43
 楼主| 发表于 2013-1-13 18:26:29 | 显示全部楼层 |阅读模式
今天在论坛中看到一个很有意思的题目,拿来分享一下:
创建table的语句:
CREATE TABLE TEST_TREE (

"ID" BIGINT NOT NULL ,

"FARTHERID" BIGINT NOT NULL ,

"NAME" VARCHAR(50) NOT NULL )  
插入数据的语句:
insert into TEST_TREE values(1001,0,'中国'),(100101,1001,'山东'),(100102,1001,'河北'),(100103,1001,' 湖北'),(10010101,100101,'济南'),(10010102,100101,'青岛'),(10010201,100102,'石家庄 '),(10010202,100102,'杨柳青'),(10010301,100103,'武汉'),(10010103,100103,'荆州')

要求sql生成的数据结构为:
中国 山东 济南
中国 山东 青岛
中国 河北 石家庄
中国 河北 杨柳青
中国 湖北 武汉
中国 湖北 荆州

该如何解决呢?
解决的办法是使用了个临时表,用递归的方式生成。语句如下:
select * from temp.TEST_TREE;

with t ( id,name,seq)
as (
select id,name,0 from temp.TEST_TREE
where fartherid=0
union all
select a.id,b.name||' '||a.name,seq +1 from temp.TEST_TREE a,t b
where a.fartherid=b.id
)
select name  from t where seq=2;
答案显示正确。

递归的过程通过如下的语句可以看出来:

with t ( id,name,seq)
as (
select id,name,0 from temp.TEST_TREE
where fartherid=0
union all
select a.id,b.name||' '||a.name,seq +1 from temp.TEST_TREE a,t b
where a.fartherid=b.id
)

select name as name0,0  from t where seq=0
union all
select name as name1 ,1  from t where seq=1
union all
select name as name2,2  from t where seq=2


结果中显示为:
'中国'0
'中国 河北'1
'中国 山东'1
'中国  湖北'1
'中国 河北 石家庄 '2
'中国 河北 杨柳青'2
'中国 山东 济南'2
'中国 山东 青岛'2
'中国  湖北 武汉'2
'中国  湖北 荆州'2
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表