這個SELECT語句帶來奇怪的結果:事先連接帶來意想不到的效果
with data(id, seqno, cs_prev_seqno, descr) as
(select 1, 1, 0, 'Id 1 Step1' from dual
union all
select 1, 2, 1, 'Id 1 Step2' from dual
union all
select 1, 3, 2, 'Id 1 Step3' from dual
union all
select 1, 4, 1, 'Id 1 Step4' from dual
union all
select 2, 1, 0, 'Id 2 Step1' from dual
union all
select 2, 2, 1, 'Id 2 Step2' from dual)
select id,
sys_connect_by_path(seqno, '/') as path,
seqno,
cs_prev_seqno,
descr,
level
from data
where id = 1
connect by prior seqno = cs_prev_seqno
start with cs_prev_seqno = 0;
我預計connect by
只是爲了與ID = 1的行完成的,但結果是:
id path seq seq_prev descr level
1 /1 1 0 Id 1 Step1 1
1 /1/2 2 1 Id 1 Step2 2
1 /1/2/3 3 2 Id 1 Step3 3
1 /1/2/3 3 2 Id 1 Step3 3
1 /1/4 4 1 Id 1 Step4 2
1 /1/2 2 1 Id 1 Step2 2
1 /1/2/3 3 2 Id 1 Step3 3
1 /1/2/3 3 2 Id 1 Step3 3
1 /1/4 4 1 Id 1 Step4 2
IE首先是connect by
是所有行完成的,後來的結果是由ID過濾。
作爲一種解決方法,下面的語句提供了正確的結果:
with data(id,
seqno,
cs_prev_seqno,
descr) as
(select 1, 1, 0, 'Id 1 Step1'
from dual
union all
select 1, 2, 1, 'Id 1 Step2'
from dual
union all
select 1, 3, 2, 'Id 1 Step3'
from dual
union all
select 1, 4, 1, 'Id 1 Step4'
from dual
union all
select 2, 1, 0, 'Id 2 Step1'
from dual
union all
select 2, 2, 1, 'Id 2 Step2'
from dual
)
,
data2 as
(select d.id,
d.seqno,
d.cs_prev_seqno,
d.id || '.' || d.seqno as id_seqno,
d.id || '.' || d.cs_prev_seqno as cs_id_prev_seqno,
d.descr
from data d)
select id,
sys_connect_by_path(seqno, '/') as path,
seqno,
cs_prev_seqno,
descr,
level
from data2
where id = 1
connect by prior id_seqno = cs_id_prev_seqno
start with cs_prev_seqno = 0;
- >
id path seq seq_prev descr level
1 /1 1 0 Id 1 Step1 1
1 /1/2 2 1 Id 1 Step2 2
1 /1/2/3 3 2 Id 1 Step3 3
1 /1/4 4 1 Id 1 Step4 2
但我想應該有實現這個更簡單的方法?提前致謝!