postgresql procedure for finding hie parent chain

白昼怎懂夜的黑 提交于 2020-01-11 13:14:11

问题


I am new to postgresql and need a little help.I have a table named products

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

I want to create a function in postgres to get the hierarchy of the parent chain of any value i pass like if i pass 4 then my output should be

id parent_id
1  Null
2  1
4  2

回答1:


I would suggest to use "recursive with" clause. Kindly check below query.

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

You can read more about recursive with clause on it official websites. Or you can check couple of examples.

Here is one link http://technobytz.com/recursive-query-evaluation-postgresql.html

Function: Try this

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';

Function Execution: select * from function_name(4)



来源:https://stackoverflow.com/questions/43672913/postgresql-procedure-for-finding-hie-parent-chain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!