sql - select recursive and order by -


i use below query select recursive top bottom
e.g
if tagid 1 rows 1 > 3,4, > 5 works fine,
want know how result order "name" @ each level(same parent id) rows 1 > 4,3 > 5 ?

i treid add order "name" after select * "tag" "tagid" = $1 not work .
, if add after select * tag_tree mess level become 1,4,5,3 not want .

create table if not exists "tag"( "tagid" serial not null, "parenttagid" integer, "name" varchar, primary key ("tagid") );  tagid | parenttagid | name | 1     |             |   | 2     |             | b   | 3     | 1           | b   | 4     | 1           |   | 5     | 3           |   |   var query = 'with recursive tag_tree (   (     select * "tag" "tagid" = $1   )   union   select child.* "tag" child     join tag_tree parent on parent."tagid" = child."parenttagid" ) select * tag_tree'; 

add order by coalesce():

with recursive tag_tree (   (     select * "tag" "tagid" = 1   )   union   select child.* "tag" child     join tag_tree parent on parent."tagid" = child."parenttagid" ) select * tag_tree order coalesce("parenttagid", 0), "name";   tagid | parenttagid | name  -------+-------------+------      1 |             |      4 |           1 |      3 |           1 | b      5 |           3 | (4 rows) 

for the documentation:

the coalesce function returns first of arguments not null. null returned if arguments null. used substitute default value null values when data retrieved display.

in case function changes null 0.


Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -