没有依赖项递归表的查询

时间:2018-12-05 03:23:02

标签: sql postgresql

我正在尝试选择一个没有依赖关系的数据库注册表(请看图中和结果)。

TABLE

结果

RESULTADO

我尝试了以下功能:

create or replace function consultar(id integer)
RETURNS TABLE(cod character varying, nom character varying) as
$$
declare
ids character varying[];
begin
ids:=(select array(select distinct tb_plan_p from 
tb_plan where 
tb_plan_p is not null order by tb_plane_p));

RETURN QUERY
select tb_plan_cod, tb_plan_des
from tb_plan
where tb_plan_cod <> any(ids) order by tb_plane_cod;
end;
$$ LANGUAGE plpgsql;

我首先尝试创建一个包含有依赖项的cod的数组,然后从结果中删除那些cod 但是我没有想要的东西

1 个答案:

答案 0 :(得分:0)

我不能完全确定我已正确理解该要求,但在我看来,您正在寻找此查询:

SELECT cod, name
FROM tb_plan AS p1
WHERE fk IS NOT NULL
  AND NOT EXISTS (
         SELECT 1
         FROM tb_plan AS p2
         WHERE p2.fk = p1.cod
      );