递归地选择行

时间:2015-10-29 19:07:33

标签: sql postgresql recursive-query

我正在使用postgresql,我尝试了解如何选择递归 我做了一个如下表的示例表,如果tagId是5,如何递归选择直到ParentTagId null(得到1,3,5行)?
如果tagId = 1如何递归地选择(获得1,3,4,5行)?

CREATE TABLE IF NOT EXISTS "Tag"(
"TagId" SERIAL NOT NULL,
"ParentTagId" integer,
"Name" varchar,
PRIMARY KEY ("TagId")
);

TagId | ParentTagId | Name |
1     |             | 1a   |
2     |             | 1b   |
3     | 1           | 2a   |
4     | 1           | 2b   |
5     | 3           | 3a   |


var tagId = 5;

var selectTagRecursiveUp = function(tagId) {
  var query = 'SELECT * FROM "Tag" WHERE "TagId" = $1';
  dbClient.query(query, [tagId], function(error, result) {    
  });
});

1 个答案:

答案 0 :(得分:2)

可以使用recursive common table expression

来完成
with recursive tag_tree as (
   select "TagId", "ParentTagId", "Name"
   from "Tag"
   where "TagId" = 5
   union all
   select parent."TagId", parent."ParentTagId", parent."Name"
   from "Tag" parent
     join tag_tree child on parent."TagId" = child."ParentTagId"
)
select *
from tag_tree;

要向另一个方向走树,你只需使用另一个"锚"查询并交换递归部分中的连接条件:

with recursive tag_tree as (
   select "TagId", "ParentTagId", "Name"
   from "Tag"
   where "TagId" = 1
   union all
   select child."TagId", child."ParentTagId", child."Name"
   from "Tag" child
     join tag_tree parent on parent."TagId" = child."ParentTagId"
)
select *
from tag_tree;

SQLFiddle示例:http://sqlfiddle.com/#!15/5ed10/1

请注意,使用带引号的标识符通常不是一个好主意。他们是值得的,他们更麻烦