【问题标题】:Select all recursive value with one query SQLite一次查询 SQLite 选择所有递归值
【发布时间】:2014-07-21 15:12:54
【问题描述】:

我还有一个案例:

首先我创建了一个表:

 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

【问题讨论】:

    标签: sql recursion


    【解决方案1】:

    这是您要找的附近的某个地方吗?

    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,并使用隐式连接)

    【讨论】:

    • 对不起,但不起作用,我想选择所有递归 = P1P2P3,而不仅仅是 P3 值。
    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多