我有另一个案例:
首先我创建了一个表:
CREATE TABLE tree(
id_tree integer PRIMARY KEY AUTOINCREMENT,
id_boss TEXT,
id_child TEXT,
answ TEXT);
插入一些值:
INSERT INTO tree(id_boss,id_child,answ) VALUES('1','8','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('1',null,'F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('8','P1','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('8','2','F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','P2','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','P3','F');
并执行查询:
WITH RECURSIVE
ancestors(id, answ) AS (
VALUES('P3', 'T')
UNION ALL
SELECT tree.id_boss, tree.answ
FROM tree JOIN ancestors ON tree.id_child = ancestors.id
)
SELECT id FROM ancestors WHERE answ = 'T';
结果是:
P3
1
对于P3
,我希望列出所有递归值,所以它会是这样的:
1 --- // P3
1 --- // P1
8 --- // P1
2 --- // P2
1 --- // P2
答案 0 :(得分:0)
这是在你想要的附近吗?
WITH seed (id, answ) as ( VALUES('P3', 'T') )
, ancestors1(id, answ) AS (
select * from seed
UNION ALL
SELECT tree.id_boss, tree.answ
FROM tree, ancestors1 where tree.id_child = ancestors1.id
)
, ancestors2(id, answ) AS (
select * from seed
UNION ALL
SELECT tree.id_boss, tree.answ
FROM tree, ancestors2 where tree.id_child = ancestors2.id
)
select id from (
select * from ancestors1
union all
select * from ancestors2
);
我不得不重新定义某些事情,以便使用db2进行编译(删除RECURSIVE,并使用隐式连接)