递归 select 行
recursively select rows
我正在使用 postgresql,我试图了解如何 select 递归。
我做了一个例子 table 如下所示,如果 tagId
是 5 如何 select 递归直到 ParentTagId
null(得到 1,3,5 行)?
如果 tagId = 1
如何 select 递归向下(获取 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" = ';
dbClient.query(query, [tagId], function(error, result) {
});
});
这可以通过 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;
要在另一个方向遍历树,您只需使用不同的 "anchor" 查询并在递归部分交换连接条件:
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
请注意,使用带引号的标识符通常不是一个好主意。麻烦多了才值得
我正在使用 postgresql,我试图了解如何 select 递归。
我做了一个例子 table 如下所示,如果 tagId
是 5 如何 select 递归直到 ParentTagId
null(得到 1,3,5 行)?
如果 tagId = 1
如何 select 递归向下(获取 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" = ';
dbClient.query(query, [tagId], function(error, result) {
});
});
这可以通过 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;
要在另一个方向遍历树,您只需使用不同的 "anchor" 查询并在递归部分交换连接条件:
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
请注意,使用带引号的标识符通常不是一个好主意。麻烦多了才值得