在PostgreSQL函数中使用递归查询

时间:2017-06-05 11:53:28

标签: sql postgresql recursive-query

我有一个包含(id,name,parent_id)列的表文件夹。父文件夹是parent_id = -1。我需要获得每个文件夹的顶级父ID。以下查询工作正常,但它不适用于spring数据jpa。

WITH RECURSIVE nodes_cte AS (
SELECT tn.id, tn.parent_id, tn.name, tn.id top_id
FROM folder AS tn 
WHERE tn.parent_id =-1
UNION ALL
SELECT c.id, c.parent_id, c.name, p.top_id
FROM nodes_cte AS p, folder AS c 
WHERE c.parent_id = p.id
)
SELECT distinct * FROM nodes_cte

如何创建postgresql函数,返回与上述查询相同的结果?

1 个答案:

答案 0 :(得分:1)

创建一个返回表的SQL函数:

CREATE OR REPLACE FUNCTION my_function()
RETURNS TABLE (id int, parent_id int, name text, top_id int)
LANGUAGE SQL AS $$
    WITH RECURSIVE nodes_cte AS (
    SELECT tn.id, tn.parent_id, tn.name, tn.id top_id
    FROM folder AS tn 
    WHERE tn.parent_id =-1
    UNION ALL
    SELECT c.id, c.parent_id, c.name, p.top_id
    FROM nodes_cte AS p, folder AS c 
    WHERE c.parent_id = p.id
    )
    SELECT distinct * FROM nodes_cte
$$;

--use:
SELECT * 
FROM my_function();

请注意,返回表中的name列应与表folder中的类型相同。