Question

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
Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top