我有两张桌子
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)
ID
和Col1
通过 FK 约束相关。我想找出所有循环引用。这里ID
和Col1
仅用于组合来自 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) 我有一个返回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)