|
今天在论坛中看到一个很有意思的题目,拿来分享一下:
创建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 |
|