我正在尝试在SQL(在Java程序中)中有效地构造查询以查找历史先决条件'适合高中课程。
基本上,我有一个名为PREREQUISITE的表,它由元组(Class_name
,Prerequisite_name
)组成。然而,一个历史先决条件'被定义为所有先决条件,以及所有先决条件的先决条件等等。
当我考虑为每个模块创建一个新表时,使用Java中的深度优先搜索来查找先前的先决条件等,但我认为它的结果非常低效。如果有人能指出如何澄清我的想法,我将非常感激。
如果需要注意的话,我会使用Oracle。
例如,样本数据:
Class_name Prerequisite_name
EC104 EC101
EC106 EC104
EC210 EC106
应提供输出:
EC101:
EC104: EC101
EC106: EC101, EC104
EC210: EC101, EC104, EC106
答案 0 :(得分:3)
详细说明RJD的答案,以下是您在Oracle中的方式。
WITH -- PREREQUISITES is just test data that you should have in your table already.. you don't need this part if you have actual tables.
prerequisites AS
(SELECT 'EC104' class_name,
'EC101' prerequisite_name
FROM DUAL
UNION ALL
SELECT 'EC106',
'EC104'
FROM DUAL
UNION ALL
SELECT 'EC210',
'EC106'
FROM DUAL),
-- CLASSES gets a distinct list of classes, which hopefully you already have in another table.. you don't need this part if you have tables
classes AS
(SELECT class_name FROM prerequisites
UNION
SELECT prerequisite_name FROM prerequisites),
-- HIERARCHY gets the historical dependencies -- you need this part
hierarchy AS
(SELECT p.*,
CONNECT_BY_ROOT class_name AS root_class_name
FROM prerequisites p
CONNECT BY class_name = PRIOR prerequisite_name)
SELECT c.class_name,
LISTAGG (h.prerequisite_name, ',') WITHIN GROUP (ORDER BY h.prerequisite_name)
FROM classes c LEFT JOIN hierarchy h ON h.root_class_name = c.class_name
GROUP BY c.class_name
ORDER BY c.class_name
答案 1 :(得分:2)
在不知道细节的情况下,Oracle是否可能希望查看分层查询。 " CONNECT BY"等