本文介紹了執(zhí)行遞歸查詢時檢測到循環(huán)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用CTE遞歸查詢來獲得低于輸出的值,但不知道為什么會這樣
使用查詢";執(zhí)行遞歸時檢測到拋出";循環(huán)。有人能告訴我我的查詢哪里錯了嗎?
我的問題:
WITH
cte (order_id,
product_id,
quantity,
cnt)
AS
(SELECT order_id,
product_id,
1 as quantity,
1 as cnt
FROM order_tbl2
UNION ALL
SELECT a.order_id,
a.product_id,
b.quantity,
b.cnt + 1
FROM order_tbl2 A INNER JOIN cte b ON a.product_id = b.product_id
WHERE b.cnt + 1 < a.quantity)
選擇訂單ID、產(chǎn)品ID、數(shù)量
來自CTE;
表/數(shù)據(jù)腳本:
CREATE TABLE ORDER_TBL2
(
ORDER_PAY DATE,
ORDER_ID VARCHAR2(10 BYTE),
PRODUCT_ID VARCHAR2(10 BYTE),
QUANTITY NUMBER(5),
PRICE NUMBER(5)
);
Insert into ORDER_TBL2
(ORDER_PAY, ORDER_ID, PRODUCT_ID, QUANTITY, PRICE)
Values
(TO_DATE('5/1/2015', 'MM/DD/YYYY'), 'ORD1', 'PROD1', 5, 5);
Insert into ORDER_TBL2
(ORDER_PAY, ORDER_ID, PRODUCT_ID, QUANTITY, PRICE)
Values
(TO_DATE('5/1/2015', 'MM/DD/YYYY'), 'ORD2', 'PROD2', 2, 10);
Insert into ORDER_TBL2
(ORDER_PAY, ORDER_ID, PRODUCT_ID, QUANTITY, PRICE)
Values
(TO_DATE('5/1/2015', 'MM/DD/YYYY'), 'ORD3', 'PROD3', 3, 25);
COMMIT;
推薦答案
在遞歸成員中,您當前只加入了a.product_id = b.product_id
,而不是a.order_id = b.order_id AND a.product_id = b.product_id
;這在這里并不直接重要,但如果不同的訂單包括相同的產(chǎn)品,則會有影響,這在現(xiàn)實世界中很可能是這樣。
但是,您的數(shù)據(jù)和查詢實際上似乎沒有周期。您似乎被ANSI連接的一個錯誤絆倒了;添加cycle
子句并不會像預期的那樣顯示任何循環(huán)行–并使其工作!;并且它可以與舊式連接一起工作:
WITH
cte (order_id,
product_id,
quantity,
cnt)
AS
(SELECT order_id,
product_id,
1 as quantity,
1 as cnt
FROM order_tbl2
UNION ALL
SELECT a.order_id,
a.product_id,
b.quantity,
b.cnt + 1
FROM order_tbl2 A, cte b
WHERE b.cnt + 1 < a.quantity
AND a.order_id = b.order_id
AND a.product_id = b.product_id
)
SELECT order_id, product_id, quantity
FROM cte;
db<>fiddle
您根本不需要加入;您可以這樣做:
WITH
cte (order_id,
product_id,
quantity,
cnt)
AS
(SELECT order_id,
product_id,
quantity,
1 as cnt
FROM order_tbl2
UNION ALL
SELECT b.order_id,
b.product_id,
b.quantity,
b.cnt + 1
FROM cte b
WHERE b.cnt < b.quantity)
SELECT order_id, product_id, 1 as quantity
FROM cte;
在最終選擇中分配固定的1數(shù)量,或:
WITH
cte (order_id,
product_id,
real_quantity,
quantity,
cnt)
AS
(SELECT order_id,
product_id,
quantity as real_quantity,
1 as quantity,
1 as cnt
FROM order_tbl2
UNION ALL
SELECT b.order_id,
b.product_id,
b.real_quantity,
b.quantity,
b.cnt + 1
FROM cte b
WHERE b.cnt < b.real_quantity)
SELECT order_id, product_id, quantity
FROM cte;
在內(nèi)部分配,需要將原始數(shù)量作為新別名進行跟蹤。
對于這兩個,我已經(jīng)從數(shù)量比較中刪除了+ 1
,因為這會使它過早停止;加上order by
,它們都會得到:
ORDER_ID | PRODUCT_ID | 數(shù)量 |
---|---|---|
ORD1 | 打印1 | 1 |
ORD1 | 打印1 | 1 |
ORD1 | 打印1 | 1 |
ORD1 | 打印1 | 1 |
ORD1 | 打印1 | 1 |
ORD2 | ProD2 | 1 |
ORD2 | ProD2 | 1 |
ORD3 | PROD3 | 1 |
ORD3 | PROD3 | 1 |
ORD3 | PROD3 | 1 |
db<>fiddle
這篇關于執(zhí)行遞歸查詢時檢測到循環(huán)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,