我的记录结构如下:
A - >乙 - > d - >的F - &GT克
A - > C - >ü - > W
乙 - > X - > Y
记录的关系只能与一个记录相关联,而不是一个记录只能有一个记录。在上述结构记录中,A'是主记录。 该表存储数据如下:
A - >乙
乙 - > d
d - >˚F
的F - &GT克
A - &以及c
所以.......
如果我提供' A'对于PL / SQL过程,它应该返回所有级别与之关联的所有子记录。我想只有递归循环才能解决这个问题? 请给我一个解决方案.. !!
提前致谢
答案 0 :(得分:1)
您可以使用递归查询来实现目标:
WITH t AS (
SELECT 'A' AS m, 'B' AS c FROM dual
UNION ALL SELECT 'B' AS m, 'D' AS c FROM dual
UNION ALL SELECT 'D' AS m, 'F' AS c FROM dual
UNION ALL SELECT 'F' AS m, 'G' AS c FROM dual
UNION ALL SELECT 'A' AS m, 'C' AS c FROM dual
UNION ALL SELECT 'C' AS m, 'U' AS c FROM dual
UNION ALL SELECT 'U' AS m, 'W' AS c FROM dual
UNION ALL SELECT 'B' AS m, 'X' AS c FROM dual
UNION ALL SELECT 'X' AS m, 'Y' AS c FROM dual
)
SELECT CONNECT_BY_ROOT(t.m) || sys_connect_by_path(c, ', ') AS list
FROM t
WHERE CONNECT_BY_ROOT(t.m) = 'A'
AND NOT EXISTS (SELECT * FROM t t2 WHERE t2.m = t.c)
CONNECT BY NOCYCLE PRIOR c = m;
以上查询返回此结果:
A, B, D, F, G
A, B, X, Y
A, C, U, W
答案 1 :(得分:1)
CREATE OR REPLACE PROCEDURE FIND_CHILD_RECORD (IN_MASTER_RECORD IN NUMBER)
IS
V_CHILD_RECORD_LIST NUMBER_LIST; -- create a number type colletion list
BEGIN
-- get all child record for the given master record
SELECT CHILD_RECORD
BULK COLLECT INTO V_CHILD_RECORD_LIST
FROM RELATED_TABLE
WHERE MASTER_RECORD_NUMBER = IN_MASTER_RECORD; -- logic holds good only if one master record is present for one child.
-- iterate over all child records
FOR IDX IN 1 .. V_CHILD_RECORD_LIST.COUNT
LOOP
-- create a global temp table to store child records
INSERT INTO TT_CHILD_RECORDS
VALUES (V_CHILD_RECORD_LIST (IDX));
COMMIT;
--call the same procedure recursively
FIND_CHILD_RECORD (V_CHILD_RECORD_LIST (IDX));
END LOOP;
END;
--TT_CHILD_RECORDS table will hold all child records for a give master.
我用递归循环编写了上面的代码来查找所有子记录。这对我有用。如果我错了,请纠正我.. :)