Connect by loop中where跟start with中的花样.
2011-01-20 14:52 Tracy. 阅读(805) 评论(0) 编辑 收藏 举报数据不是我的,不过例子是我的。
首先,大家平时使用sql中如果用到connect by loop语法。如果有用到where,start with条件,不知道怎么理解.
有时候where可能是先于start with执行的,有时候是晚于start with执行的,关键在于你是否join.
测试数据
create table test1(superid varchar2(20),id varchar2(20));
insert into test1 values('0','1');
insert into test1 values('0','2');
insert into test1 values('1','11');
insert into test1 values('1','12');
insert into test1 values('2','21');
insert into test1 values('2','22');
insert into test1 values('11','111');
insert into test1 values('11','112');
insert into test1 values('12','121');
insert into test1 values('12','122');
insert into test1 values('21','211');
insert into test1 values('21','212');
insert into test1 values('22','221');
insert into test1 values('22','222');
commit;
select * from test1
这里我先用join,111这个条件会被先执行,这样再做start with的时候会查不到记录,因为他的范围这时候只有1条,superid是11,不是0。
--------------Join -------------
select level||' layer',lpad(' ',level*5)||id id ,connect_by_isleaf,substr( sys_connect_by_path(id,'>'),2)
from test1 ,(select 111 col from dual) tmp
where tmp.col=to_number(test1.id)
start with superid = '0' connect by prior id=superid;
然后我不用join,这时候我们能取到值,因为我先执行的start with,111是其中的子集,所以这个查询是有数据的。
------------------not join-----------------
select level||' layer',lpad(' ',level*5)||id id ,connect_by_isleaf,substr( sys_connect_by_path(id,'>'),2)
from test1
where 111=to_number(test1.id)
start with superid = '0' connect by prior id=superid;
大家通过这个例子,应该想到什么时候我们要去做join,什么时候不要。join可能会大大提高语句的效率因为我们会先执行where对吧。本贴原创。
本文来自博客园,作者:Tracy.,转载请注明原文链接:https://www.cnblogs.com/tracy/archive/2011/01/20/1940211.html