我有一个包含产品的表,每个产品都有用于制造的其他产品。用于制造母产品的产品也可以制造,也可以包含其他制造产品。示例:
ID_PRODUCT_MATERIAL PRODUCTION ID_MATERIAL
1 2 2
1 2 3
1 2 4
2 1 9
2 1 10
3 1 8
8 1 5
产品1需要产品2,3和4,但也制造产品2和3。产品2需要9和10,而3需要8,最后8需要5。在这种情况下,我们在此处具有级别,产品1在级别1,产品2,3和4在级别2,产品8在级别3。试图使用递归级别的层次结构进行选择,但事实证明,它并不是一个层次结构。下面使用的SELECT向我返回以下错误:
SQL error: ORA-32044: Cycle detected when executing the recursive WITH query
WITH CTE (ID_PRODUCT_MATERIAL,PRODUCTION,ID_MATERIAL) AS (
SELECT ID_PRODUCT_MATERIAL,
PRODUCTION,
ID_MATERIAL,
PRODNR_MAT
FROM MATERIAL
UNION ALL
SELECT ID_PRODUCT_MATERIAL,
M.PRODUCTION,
M.ID_MATERIAL,
FROM MATERIAL M
INNER JOIN CTE C
ON M.ID_PRODUCT_MATERIAL = C.ID_MATERIAL
)
SELECT * FROM CTE;
ID_PRODUCT_MATERIAL和ID_MATERIAL列是从产品表派生的。在这种情况下如何进行?这是表格的结构:
CREATE TABLE PRODUCT(
ID_PRODUCT NUMBER(6,0) PRIMARY KEY,
NAME VARCHAR2(200),
WEIGHT NUMBER(6,2),
PRICE NUMBER(6,2)
);
CREATE TABLE PRODUCTION(
ID_PRODUCT_PRODUCTION NUMBER(6,0) PRIMARY KEY,
PRODUCTION NUMBER(3,0),
CONSTRAINT FK_PRODUCTIONPRODUCT FOREIGN KEY(ID_PRODUCT_PRODUCTION) REFERENCES PRODUCT(ID_PRODUCT)
);
CREATE TABLE MATERIAL(
ID_PRODUCT_MATERIAL NUMBER(6,0),
PRODUCTION NUMBER(3,0),
ID_MATERIAL NUMBER(6,0),
CONSTRAINT PK_MATERIAL PRIMARY KEY(ID_PRODUCT_MATERIAL, ID_MATERIAL),
CONSTRAINT FK_PRODUCT FOREIGN KEY (ID_PRODUCT_MATERIAL) REFERENCES PRODUCT(ID_PRODUCT)
CONSTRAINT FK_PRODUCTION FOREIGN KEY (ID_PRODUCT_MATERIAL) REFERENCES PRODUCT(ID_PRODUCT_PRODUCTION)
CONSTRAINT FK_PRODUCT FOREIGN KEY (ID_MATERIAL) REFERENCES PRODUCT(ID_PRODUCT)
);
INSERT INTO PRODUCT (ID_PRODUCT,NAME,WEIGHT,PRICE) VALUES (1,'PRODUCT A',10,5),
(2,'PRODUCT B',10,5),
(3,'PRODUCT C',10,5),
(4,'PRODUCT D',10,5),
(5,'PRODUCT E',10,5),
(6,'PRODUCT F',10,5),
(7,'PRODUCT G',10,5),
(8,'PRODUCT H',10,5),
(9,'PRODUCT I',10,5),
(10,'PRODUCT J',10,5)
INSERT INTO PRODUCT (ID_PRODUCT_PRODUCTION,PRODUCTION) VALUES (1,2),
(2,1),
(3,1)
INSERT INTO MATERIAL (ID_PRODUCT_MATERIAL, PRODUCTION, ID_MATERIAL) VALUES (1,2,2),
(1,2,3),
(1,2,4),
(2,1,9),
(2,1,10),
(3,1,8)
在第三张表中,您有多个问题:
我已经这样纠正了它:
CREATE TABLE MATERIAL( ID_PRODUCT_MATERIAL NUMBER(6,0), PRODUCTION NUMBER(3,0), ID_MATERIAL NUMBER(6,0), CONSTRAINT PK_MATERIAL PRIMARY KEY(ID_PRODUCT_MATERIAL, ID_MATERIAL), CONSTRAINT FK_PRODUCT FOREIGN KEY (ID_PRODUCT_MATERIAL) REFERENCES PRODUCT(ID_PRODUCT), CONSTRAINT FK_PRODUCTION FOREIGN KEY (ID_PRODUCT_MATERIAL) REFERENCES PRODUCTION(ID_PRODUCT_PRODUCTION), CONSTRAINT FK_PRODUCT2 FOREIGN KEY (ID_MATERIAL) REFERENCES PRODUCT(ID_PRODUCT) );
您能检查一下并给我们正确的表定义吗?这被添加为询问,因为它太大了,无法发表评论...