Max*_*Max 6 sql postgresql tree recursion common-table-expression
我正在尝试将Postgres中的函数转换为select我打算用作视图的查询.原因是我想通过select带有where子句的查询从客户端访问它,而不是像使用函数那样使用参数.该表表示树(和邻接列表),定义如下:
CREATE TABLE tree (
id serial primary key,
parent_id int references tree(id)
);
INSERT INTO tree (id, parent_id) VALUES
(1,null)
, (2,1), (3,2), (4,3), (5,3)
, (6,5), (7,6), (8,4), (9,8)
, (10,9), (11,9), (12,7)
, (13,12), (14,12), (15,11)
, (16,15), (17,16), (18,14)
, (19,13), (20,19), (21,20);
SELECT setval ('tree_id_seq', 21); -- reset sequence
-- This produces a tree like:
-- +-- <10>
-- /
-- +-- <4> -- <8> --- <9> -+- <11> --- <15> --- <16> --- <17>
-- /
-- <1> --- <2> --- <3> -+
-- \
-- +-- <5> --- <6> --- <7> --- <12> -+- <14> --- <18>
-- \
-- \
-- \
-- \
-- +-- <13> --- <19> --- <20> --- <21>
--
Run Code Online (Sandbox Code Playgroud)
要按顺序从树中的任何节点获取路径到根,我使用此函数:
create or replace function _tree(rev int)
returns table(id int, parent_id int, depth int) as $$
declare
sql text;
begin
sql = 'WITH RECURSIVE tree_list(id, parent_id, depth) AS (
SELECT id, parent_id, 1 FROM tree WHERE id = ' || rev ||
'UNION
SELECT p.id, p.parent_id, r.depth + 1
FROM tree p, tree_list r
WHERE p.id = r.parent_id
)
SELECT id, parent_id, depth FROM tree_list order by id;';
return query execute sql;
end;
$$ language plpgsql;
Run Code Online (Sandbox Code Playgroud)
查询看起来像select * from _tree(15).问题是如何将此功能转换为视图,所以我可以打电话select * from tree where id <= 15.此外,视图是否以与函数相同的速度执行(即在执行查询时是否考虑where子句)?
你可以使用这样的东西:
CREATE OR REPLACE VIEW v_tree AS
SELECT tr.id as start,
(_tree(tr.id)).id,
(_tree(tr.id)).parent_id,
(_tree(tr.id)).depth
FROM tree tr;
Run Code Online (Sandbox Code Playgroud)
它是从所有节点到根的路径的视图。
然后使用类似的东西:
SELECT *
FROM v_tree
WHERE start = 15;
Run Code Online (Sandbox Code Playgroud)
以获得想要的路径。
它对我的示例数据有用,但我还没有测试它的性能。
更新查询以_tree仅调用一次:
CREATE OR REPLACE VIEW v_tree AS
SELECT t_tree.start,
(t_tree.node).id,
(t_tree.node).parent_id,
(t_tree.node).depth
FROM (SELECT tr.id as start,
_tree(tr.id) as node
FROM tree tr) t_tree;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1229 次 |
| 最近记录: |