SQLite : with clouse result weird

与世无争的帅哥 提交于 2019-12-25 02:20:05

问题


Now i can implement sqlite3 3.8.4.3 within my android app, i found an awesome library name sqlcipher , :)

and now here again i'm trying to implement recursive function within an android app;

i try (recursive function) from 'cmd' windows:

i create a table :

 CREATE TABLE tree(
 id_tree integer PRIMARY KEY AUTOINCREMENT,
 id_boss TEXT,
 id_child TEXT,
 answ TEXT);

insert some value :

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

and then i running a recursive query that now availabe for 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;

the weird result :

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

why the end of the tree is selected number 2 row value each group ? how to make a query so the result should like this ?

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

回答1:


This query sorts the records only by the 2nd column, the level.

To specify the order of records at the same level, you have to add the appropriate column to the ORDER BY clause. In this case, this is probably the id_tree value, which you have to add to the SELECT clause so that it is available:

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;


来源:https://stackoverflow.com/questions/23499988/sqlite-with-clouse-result-weird

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!