如何CONNECT BY
执行和评估查询 - 一步一步(通过示例)。
假设我们有下表和一个通过查询连接:
select * from mytable;
X
----------
1
2
3
4
SELECT level, m.*
FROM mytable m
START with x = 1
CONNECT BY PRIOR x +1 = x OR PRIOR x + 2 = x
ORDER BY level;
步骤1:
从表mytable
中选择满足START WITH
条件的行,将LEVEL = 1分配给返回的结果集:
CREATE TABLE step1 AS
SELECT 1 "LEVEL", X from mytable
WHERE x = 1;
SELECT * FROM step1;
LEVEL X
---------- ----------
1 1
第2步
将等级提高 1:
LEVEL = LEVEL + 1
mytable
使用CONNECT BY
条件作为连接条件连接上一步返回的结果集。
在这个子句PRIOR column-name
中指的是上一步返回的结果集,simplecolumn-name
指的是mytable
表:
CREATE TABLE step2 AS
SELECT 2 "LEVEL", mytable.X from mytable
JOIN step1 "PRIOR"
ON "PRIOR".x +1 = mytable.x or "PRIOR".x + 2 = mytable.x;
select * from step2;
LEVEL X
---------- ----------
2 2
2 3
步骤 x+1
重复 #2 直到最后一个操作返回一个空的结果集。
第 3 步
CREATE TABLE step3 AS
SELECT 3 "LEVEL", mytable.X from mytable
JOIN step2 "PRIOR"
ON "PRIOR".x +1 = mytable.x or "PRIOR".x + 2 = mytable.x;
select * from step3;
LEVEL X
---------- ----------
3 3
3 4
3 4
第4步
CREATE TABLE step4 AS
SELECT 4 "LEVEL", mytable.X from mytable
JOIN step3 "PRIOR"
ON "PRIOR".x +1 = mytable.x or "PRIOR".x + 2 = mytable.x;
select * from step4;
LEVEL X
---------- ----------
4 4
第 5 步
CREATE TABLE step5 AS
SELECT 5 "LEVEL", mytable.X from mytable
JOIN step4 "PRIOR"
ON "PRIOR".x +1 = mytable.x or "PRIOR".x + 2 = mytable.x;
select * from step5;
no rows selected
第 5 步没有返回任何行,所以现在我们完成查询
最后一步
UNION ALL
所有步骤的结果并将其作为最终结果返回:
SELECT * FROM step1
UNION ALL
SELECT * FROM step2
UNION ALL
SELECT * FROM step3
UNION ALL
SELECT * FROM step4
UNION ALL
SELECT * FROM step5;
LEVEL X
---------- ----------
1 1
2 2
2 3
3 3
3 4
3 4
4 4
现在让我们将上述过程应用于您的查询:
SELECT * FROM dual;
DUMMY
-----
X
SELECT LEVEL FROM DUAL CONNECT BY rownum>5;
步骤1
由于查询不包含该START WITH
子句,Oracle 会从源表中选择所有记录:
CREATE TABLE step1 AS
SELECT 1 "LEVEL" FROM dual;
select * from step1;
LEVEL
----------
1
第2步
CREATE TABLE step2 AS
SELECT 2 "LEVEL" from dual
JOIN step1 "PRIOR"
ON rownum > 5
select * from step2;
no rows selected
由于最后一步没有返回任何行,我们将完成我们的查询。
最后一步
SELECT * FROM step1
UNION ALL
SELECT * FROM step2;
LEVEL
----------
1
最后一个查询的分析:
select level from dual connect by rownum<10;
我把作业留给你。