【发布时间】:2021-07-19 01:42:00
【问题描述】:
几天前,我在服务器上安装了 DB2 LUW (11.5) 来玩玩。 现在我想做一些递归SQL(Recursive Common Table Expression):
让我展示一下我是如何设置的:
drop table relations;
create table relations (id int, parent int);
insert into relations values(0,NULL);
insert into relations values(1,0);
insert into relations values(2,1);
insert into relations values(3,1);
insert into relations values(4,3);
insert into relations values(5,0);
insert into relations values(6,5);
insert into relations values(7,5);
insert into relations values(8,6);
insert into relations values(9,7);
insert into relations values(10,0);
insert into relations values(11,1);
commit;
现在我想查看表格中的层次结构。所以我尝试了以下方法:
with recur(id, parent, level) as
(
select rel.id id, rel.parent parent, 0 level from relations rel where rel.id=0
union all
select rel.id, rel.parent, rec.level+1 from recur rec, relations rel where rec.id=rel.parent
and rec.level<10
)
select id, lpad(parent, level*2, ' ') from recur;
这给了我:
ID PARENT
----------- ------------------
0 -
1 0
5 0
10 0
2 1
3 1
11 1
6 5
7 5
4 3
8 6
9 7
这是(对我而言):“搜索广度优先” 我希望看到的是“搜索深度优先”
所以我这样做了:
with recur(id, parent, level) as
(
select rel.id id, rel.parent parent, 0 level from relations rel where rel.id=0
union all
select rel.id, rel.parent, rec.level+1 from recur rec, relations rel where rec.id=rel.parent
and rec.level<10
)
search depth first by parent set ord
select id, lpad(parent, level*2, ' ') parent from recur order by ord;
但这传递给我:
SQL0104N An unexpected token "search depth first by parent set ord sel" was
found following "t and rec.level<10 )". Expected tokens may include:
"<values>". SQLSTATE=42601
现在不知道如何解决。我(想我)已经尝试了很多可能的解决方案。但没有一个奏效。 我开始相信 DB2 LUW (11.5) 不知道搜索深度优先。或者必须进行一些设置以使 DB2 意识到“SDF”的可能性。
我的问题给大家: 如何解决这个问题呢?如何让搜索深度优先发挥作用?
从积极的方面来说....追随作品就像一个魅力....但这不是我想知道的:-)
select id, lpad(parent, level*2, ' ') parent, level
from relations
start with id=0
connect by prior id=parent;
ID PARENT LEVEL
----------- ---------- -----------
0 - 1
1 0 2
2 1 3
3 1 3
4 3 4
11 1 3
5 0 2
6 5 3
8 6 4
7 5 3
9 7 4
10 0 2
这就像一个魅力,但我不得不在数据库中进行切换(并重新启动):
db2set DB2_COMPATIBILITY_VECTOR=08
【问题讨论】:
-
学习使用正确的、明确的、标准的、可读的
JOIN语法。 -
@GordonLinoff 据我所知,DB2 不允许在递归 CTE 中使用连接语法,而只允许使用旧式连接。