用于查找 hie 父链的 postgresql 过程

postgresql procedure for finding hie parent chain

我是 postgresql 的新手,需要一点 help.I 有一个 table 命名的产品

ID Product Parent_ID
1  laptop   Null
2  Camera   1
3  Iphone   1
4  Mouse    2
5  Printer  2
6  Scanner  3
7  HardDisk 3

我想在 postgres 中创建一个函数来获取我传递的任何值的父链的层次结构,如果我传递 4,那么我的输出应该是

id parent_id
1  Null
2  1
4  2

我建议使用 "recursive with" 子句。请检查以下查询。

WITH RECURSIVE recursiveTable AS (
SELECT id, parent_id  
FROM table_name
WHERE id = 4  -- you can pass an id here to get the output
UNION ALL
SELECT t.id, t.parent_id
FROM table_name t                  
JOIN recursiveTable rt ON t.id = rt.parent_id 
)
SELECT * FROM recursiveTable

你可以在它的官方网站上阅读更多关于recursive with clause的内容。或者你可以检查几个例子。

这是一个link http://technobytz.com/recursive-query-evaluation-postgresql.html

功能:试试这个

CREATE OR REPLACE FUNCTION function_name(param_id INT) 
RETURNS TABLE (
id INT,
parent_id INT
) 
AS $$
BEGIN
RETURN QUERY WITH RECURSIVE recursiveTable AS (
SELECT t.id, t.parent_id  
FROM table_name t
WHERE t.id = param_id  -- you can pass an id here to get the output
UNION ALL
SELECT t.id, t.parent_id 
FROM table_name t                  
JOIN recursiveTable rt ON t.id = rt.parent_id
)
SELECT * FROM recursiveTable ;

END; $$ 

LANGUAGE 'plpgsql';

函数执行: select * 来自 function_name(4)