select recursive and order by

时间:2015-10-31 00:06:08

标签: sql postgresql recursion recursive-query

I use below query to select recursive top to bottom e.g If tagId is 1 will get rows 1 > 3,4, > 5 now works fine, but I want to know how to get result order by "Name" at each level(same parent id) get rows 1 > 4,3 > 5 ? I treid add ORDER BY "Name" after SELECT * FROM "Tag" WHERE "TagId" = $1 but not work . and if add after SELECT * FROM tag_tree that will mess level become 1,4,5,3 not what I want . CREATE TABLE IF NOT EXISTS "Tag"( "TagId" SERIAL NOT NULL, "ParentTagId" integer, "Name" varchar, PRIMARY KEY ("TagId") ); TagId | ParentTagId | Name | 1 | | a | 2 | | b | 3 | 1 | b | 4 | 1 | a | 5 | 3 | a | var query = 'WITH RECURSIVE tag_tree AS ( ( SELECT * FROM "Tag" WHERE "TagId" = $1 ) UNION ALL SELECT child.* FROM "Tag" child JOIN tag_tree parent on parent."TagId" = child."ParentTagId" ) SELECT * FROM tag_tree';

1 个答案:

答案 0 :(得分:1)

使用ORDER BY添加coalesce()

WITH RECURSIVE tag_tree AS (
  (
    SELECT * FROM "Tag" WHERE "TagId" = 1
  )
  UNION ALL
  SELECT child.* FROM "Tag" child
    JOIN tag_tree parent on parent."TagId" = child."ParentTagId"
)
SELECT * FROM tag_tree
ORDER BY coalesce("ParentTagId", 0), "Name";

 TagId | ParentTagId | Name 
-------+-------------+------
     1 |             | a
     4 |           1 | a
     3 |           1 | b
     5 |           3 | a
(4 rows)

the documentation

  

COALESCE函数返回其第一个参数   空值。仅当所有参数都为null时才返回Null。经常这样   用于在数据时用空值替换默认值   检索显示。

在这种情况下,该功能会将null更改为0