我是postgresql的新手,需要一些帮助。我有一个名为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
我想在postgres中创建一个函数来获取我传递的任何值的父链的层次结构,如果我传递4然后我的输出应该是
id parent_id
1 Null
2 1
4 2
答案 0 :(得分:0)
我建议使用"递归"条款。请检查以下查询。
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
您可以在官方网站上阅读有关递归条款的更多信息。或者您可以查看几个示例。
这是一个链接 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 * from function_name(4)