我有一个包含(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函数,返回与上述查询相同的结果?
答案 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
中的类型相同。