PostgreSQL에서 재귀 쿼리를 사용하여 전이 폐쇄를 설명하는 간단한 예제를 만들었습니다.전이 폐쇄에 사용되는 재귀 쿼리
그러나 내 재귀 쿼리를 사용하면 문제가 해결됩니다. 문법에 익숙하지 않아서이 요청이 전적으로 나에게 불쾌감을 줄 수 있습니다. 그 때문에 사전에 사과드립니다. 쿼리를 실행하면 노드 1이 경로 결과에서 반복되는 것을 볼 수 있습니다. 누군가 SQL을 조정하는 방법을 알아내는 데 도움을 줄 수 있습니까?
/* 1
/ \
2 3
/\ /
4 5 6
/
7
/\
8 9
*/
create table account(
acct_id INT,
parent_id INT REFERENCES account(acct_id),
acct_name VARCHAR(100),
PRIMARY KEY(acct_id)
);
insert into account (acct_id, parent_id, acct_name) values (1,1,'account 1');
insert into account (acct_id, parent_id, acct_name) values (2,1,'account 2');
insert into account (acct_id, parent_id, acct_name) values (3,1,'account 3');
insert into account (acct_id, parent_id, acct_name) values (4,2,'account 4');
insert into account (acct_id, parent_id, acct_name) values (5,2,'account 5');
insert into account (acct_id, parent_id, acct_name) values (6,3,'account 6');
insert into account (acct_id, parent_id, acct_name) values (7,4,'account 7');
insert into account (acct_id, parent_id, acct_name) values (8,7,'account 8');
insert into account (acct_id, parent_id, acct_name) values (9,7,'account 9');
WITH RECURSIVE search_graph(acct_id, parent_id, depth, path, cycle) AS (
SELECT g.acct_id, g.parent_id, 1,
ARRAY[g.acct_id],
false
FROM account g
UNION ALL
SELECT g.acct_id, g.parent_id, sg.depth + 1,
path || g.acct_id,
g.acct_id = ANY(path)
FROM account g, search_graph sg
WHERE g.acct_id = sg.parent_id AND NOT cycle
)
SELECT path[1] as Child,parent_id as Parent,path || parent_id as path FROM search_graph
ORDER BY path[1],depth;
테스트 설정은 유용하고 유용하지만 결과가 정확히 같아야한다고 설명해주십시오. '이행 적 폐쇄'라는 핵심 단어를 던지면 설명이 충분하지 않습니다. –