SQLite:with子句结果很奇怪

时间:2014-05-06 16:22:41

标签: android recursion sqlite

现在我可以在我的Android应用程序中实现sqlite3 3.8.4.3,我找到了一个很棒的库名sqlcipher,:))

现在又来了,我试图在Android应用程序中实现递归函数;

我尝试(递归功能)来自' cmd'窗口:

我创建了一个表:

 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','2','T');
 INSERT INTO tree(id_boss,id_child,answ) VALUES('1','3','F');
 INSERT INTO tree(id_boss,id_child,answ) VALUES('2','P1','T');
 INSERT INTO tree(id_boss,id_child,answ) VALUES('2','4','F');
 INSERT INTO tree(id_boss,id_child,answ) VALUES('3','P2','T');
 INSERT INTO tree(id_boss,id_child,answ) VALUES('3','8','F');

然后我运行一个现在可用于sqlite 3.8的递归查询:

 WITH RECURSIVE
 under_alice(name,level) AS (
   VALUES('1','0')
   UNION ALL
   SELECT tree.id_child, under_alice.level+1
     FROM tree, under_alice
    WHERE tree.id_boss=under_alice.name 
    ORDER BY 2 DESC
    )
   SELECT  substr('..........',1,level*3) || name FROM under_alice;

奇怪的结果:

  1
  ...2
  ......4
  ......P1
  ...3
  ......8
  ......P2

为什么树的末尾被选中每组2个行值? 如何进行查询,结果应该是这样的?

  1
  ...2
  ......P1
  ......4
  ...3
  ......P2
  ......8

1 个答案:

答案 0 :(得分:2)

此查询仅按第二列(级别)对记录进行排序。

要指定同一级别的记录顺序,必须将相应的列添加到ORDER BY子句中。 在这种情况下,这可能是id_tree值,您必须将其添加到SELECT子句中以便它可用:

WITH RECURSIVE
under_alice(name,level,order_nr) AS (
  VALUES('1','0',0)
  UNION ALL
  SELECT tree.id_child, under_alice.level+1, tree.id_tree
    FROM tree, under_alice
   WHERE tree.id_boss=under_alice.name 
   ORDER BY 2 DESC, 3
)
SELECT substr('..........',1,level*3) || name FROM under_alice;