选择特定值SQLite

时间:2014-05-17 11:37:24

标签: sqlite

我有一个问题,我正在使用sqlite,

首先我创建了一个表:

 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
 ancestor(id) AS (
  VALUES('P3')
  UNION ALL
  SELECT tree.id_boss
  FROM tree JOIN ancestor ON tree.id_child = ancestor.id
  )
 SELECT id FROM ancestor;

结果是:

  P3
  2
  8
  1

我的问题是,如何查询选择'T'值中的id_boss并忽略'F'中的所有内容?

结果应该是这样的:

  P3
  1

2 个答案:

答案 0 :(得分:1)

您无法从CTE内部过滤掉F条记录,因为这会破坏树中的连接。 相反,您必须返回answ值,并在第二步中将其用作过滤器:

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';

答案 1 :(得分:0)

尝试:

带着回归  祖先(id)AS(   VALUES(' P3')   UNION ALL   SELECT tree.id_boss   FROM tree JOIN祖先on tree.id_child = ancestor.id和tree。 ANSW =' F'   )  SELECT id FROM ancestor;