简体   繁体   English

SQL-列出所有先决条件(如循环)

[英]SQL - Listing all prerequisites (Like a loop)

(I'm using SQL Plus, although I don't think that would matter too much) (我使用的是SQL Plus,尽管我认为这不太重要)

Okay my database structure looks similar to this: 好的,我的数据库结构看起来像这样:

CREATE TABLE MODULE (
  module_code       INT,
  PRIMARY KEY (module_code)
);

CREATE TABLE PREREQUISITES (
  module_code       INT,
  prerequisite_code VARCHAR(6),
  FOREIGN KEY (module_code) REFERENCES MODULE(module_code),
  FOREIGN KEY (prerequisite_code) REFERENCES MODULE(module_code)
);

So the data may look like this: 因此数据可能如下所示:

MODULE:
5
15
20
100

PREREQUISITES:
100  20
100  15
15   5

My question is, is there a way to list all prerequisites for a module (eg prerequisites of 100 is: 20, 15 & 5 (because 15 has a prerequisite of 5) or must this be done programmatically. 我的问题是,是否有办法列出模块的所有先决条件(例如100的先决条件是:20、15和5(因为15的先决条件是5)或必须以编程方式完成。

I'm also aware there could be circular references. 我也知道可能会有循环引用。 Again I can think of a way to do this programmatically but is there a way to detect this using just SQL. 同样,我可以想到一种以编程方式执行此操作的方法,但是有一种方法可以仅使用SQL来检测到此问题。

Actually, the RDBMS you are using maters completely for what you are trying to accomplish. 实际上,您要使用的RDBMS完全可以满足您要完成的任务。 You are storing your hierarchical data in an adjacency list model. 您将层次结构数据存储在adjacency list模型中。 Since you are using oracle , you can use CONNECT BY to traverse the tree: 由于您使用的是oracle ,因此可以使用CONNECT BY遍历树:

SELECT * 
FROM PREREQUISITES
START WITH module_code = 100
CONNECT BY module_code = PRIOR prerequisite_code

And here's a good article on the subject: http://explainextended.com/2009/09/28/adjacency-list-vs-nested-sets-oracle/ 这是一篇关于该主题的好文章: http : //explainextended.com/2009/09/28/adjacency-list-vs-nested-sets-oracle/


If duplicates and infinite loops are potential concerns, you can use nocylcle to prevent the infinite loops and a subquery to return the distinct results: 如果重复和无限循环是潜在的问题,则可以使用nocylcle防止无限循环,并使用子查询返回distinct结果:

SELECT * 
FROM (SELECT DISTINCT module_code, prerequisite_code FROM PREREQUISITES) T
START WITH module_code = 100
CONNECT BY NOCYCLE module_code = PRIOR prerequisite_code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM