小编GaN*_*RdE的帖子

查询以查找循环引用

我有两张桌子

ID  Task
1   1
2   2
3   3
4   4

Col1  depend
2     3
2     4
3     1
4     2
Run Code Online (Sandbox Code Playgroud)

IDCol1通过 FK 约束相关。我想找出所有循环引用。这里IDCol1仅用于组合来自 2 个表的行,例如:

Task 1 can start anytime.
Task 2 can start only after completion of 3, 4 etc

1 –
2 – 3, 4, 1, 2   -- for 2 there is circular dependency
3 – 1
4 – 2, 3, 4      -- also circular dependency
Run Code Online (Sandbox Code Playgroud)

案例2:

Col1  depend
2 …
Run Code Online (Sandbox Code Playgroud)

postgresql cte postgresql-9.2 recursive

6
推荐指数
1
解决办法
3676
查看次数

如何引用函数返回的记录的各个列?

我有一个返回setof record类型的函数。

CREATE TYPE CIR_TYPE AS
(
    ID integer,
    path text,
    cycle boolean
);

CREATE OR REPLACE FUNCTION circular_ref() RETURNS setof CIR_TYPE AS $body$

DECLARE
    r CIR_TYPE;

BEGIN
    For r in WITH RECURSIVE graph(ID, path, cycle) AS (
                SELECT id AS id
                     , ARRAY[parentid, id] AS path
                     , (parentid = id) AS cycle    
                FROM  mytable

                UNION ALL

                SELECT d.id, d.parentid ||path, d.parentid = ANY(path)
                FROM   graph g
                JOIN   mytable d ON d.id = g.path[1]
                WHERE  NOT g.cycle
             ) …
Run Code Online (Sandbox Code Playgroud)

postgresql postgresql-9.1

4
推荐指数
1
解决办法
2454
查看次数