startwith...connectby用法简介sql有向图问题期待新解决方案/*******************************************************************************通过STARTWITH...CONNECTBY...子句来实现SQL的层次查询.自从Oracle9i开始,可以通过SYS_CONNECT_BY_PATH函数实现将父节点到当前行内容以“path”或者层次元素列表的形式显示出来。自从Oracle10g中,还有其他更多关于层次查询的新特性。例如,有的时候用户更关心的是每个层次分支中等级最低的内容。那么你就可以利用伪列函数CONNECT_BY_ISLEAF来判断当前行是不是叶子。如果是叶子就会在伪列中显示“1”,如果不是叶子而是一个分支(例如当前内容是其他行的父亲)就显示“0”。在Oracle10g之前的版本中,如果在你的树中出现了环状循环(如一个孩子节点引用一个父亲节点),Oracle就会报出一个错误提示:“ORA-01436:CONNECTBYloopinuserdata”。如果不删掉对父亲的引用就无法执行查询操作。而在Oracle10g中,只要指定“NOCYCLE”就可以进行任意的查询操作。与这个关键字相关的还有一个伪列——CONNECT_BY_ISCYCLE,如果在当前行中引用了某个父亲节点的内容并在树中出现了循环,那么该行的伪列中就会显示“1”,否则就显示“0”。Thestartwith..connectbyclausecanbeusedtoselectdatathathasahierarchicalrelationship(usuallysomesortofparent->child,boss->employeeorthing->parts).Itisalsobeingusedwhenansqlexecutionplanisexplained.syntax:select...[startwithinitial-condition]connectby[nocycle]recurse-conditionlevelWithlevelitispossibletoshowthelevelinthehierarchicalrelationofallthedata.--oracle9isys_connect_by_pathWithsys_connect_by_pathitispossibletoshowtheentirepathfromthetopleveldowntothe'actual'child.--oracle10gconnect_by_rootconnect_by_rootisanewoperatorthatcomeswithOracle10gandenhancestheabilitytoperformhierarchicalqueries.connect_by_is_leafconnect_by_isleafisanewoperatorthatcomeswithOracle10gandenhancestheabilitytoperformhierarchicalqueries.connect_by_iscycleconnect_by_is_cycleisanewoperatorthatcomeswithOracle10gandenhancestheabilitytoperformhierarchicalqueries.--startwith...connectby...的处理机制Howmustastartwith...connectbyselectstatementbereadandinterpreted?IfOracleencounterssuchanSQLstatement,itproceedsasdescribedinthefollowingpseudecode.forrecin(select*fromsome_table)loopifFULLFILLS_START_WITH_CONDITION(rec)thenRECURSE(rec,rec.child);endif;endloop;procedureRECURSE(recinMATCHES_SELECT_STMT,new_parentINfield_type)isbeginAPPEND_RESULT_LIST(rec);forrec_recursein(select*fromsome_table)loopifFULLFILLS_CONNECT_BY_CONDITION(rec_recurse.child,new_parent)thenRECURSE(rec_recurse,rec_recurse.child);endif;endloop;endprocedureRECURSE;createdbyzhouwf07262006.*******************************************************************************/--创建测试表,增加测试数据createtabletest(superidvarchar2(20),idvarchar2(20));insertintotestvalues('0','1');insertintotestvalues('0','2');insertintotestvalues('1','11');insertintotestvalues('1','12');insertintotestvalues('2','21');insertintotestvalues('2','22');insertintotestvalues('11','111');insertintotestvalues('11','112');insertintotestvalues('12','121');insertintotestvalues('12','122');insertintotestvalues('21','211');insertintotestvalues('21','212');insertintotestvalues('22','221');insertintotestvalues('22','222');commit;--层次查询示例selectlevel||'层',lpad('',level*5)||ididfromteststartwithsuperid='0'connectbypriorid=superid;selectlevel||'层',connect_by_isleaf,lpad('',level*5)||ididfromteststartwithsuperid='0'connectbypriorid=superid;--给出两个以前在"数据库字符串分组相加之四"中的例子来理解sta...