2010-04-1514:27byTracy.,1734visits,收藏,编辑LevelisapseudocolumnusedwithCONNECTBYanddenotesthenodelevelofthetreestructure.Forexample,giventhefollowingdepartment/sub-departmentlayeringarchitecture,wehaveanAccountingdepartmentwithinaFinancialsdepartmentwithinaSoftwaredepartment,thatis,SoftwareOSFinancialsSpreadsheetsAccountingTheexistenceofavalid\"parent\"departmentcanbeenforcedwithaforeignkeyconstraintonadepartmentnamecolumn.ThisconstraintensuresthatIFadepartmenthasaparent,itisanexistingdepartmentinthesametable.CREATETABLEdept(dept_nameVARCHAR2(20)PRIMARYKEY,parent_nameVARCHAR2(20),CONSTRAINTfk_dept2_parent_nameFOREIGNKEY(parent_name)REFERENCESdept);TheresultofSELECT*FROMDEPTis:DEP_NAME--------SoftwareOSFinancialsSpreadsheetAccountingPARENT_NAME------------NULLSoftwareSoftwareFinancialsFinancialsThefollowingSQLstatementusesLEVELtodenotethelevelnumberofthenodeinthetreestructure.SELECTLEVEL,parent_name,dept_nameFROMdeptCONNECTBYpriordept_name=parent_nameSTARTWITHdept_name='Software'ORDERBYLEVEL;Theresultis:LEVELPARENT_NAMEDEPT_NAME--------------------------------------------------12Software2SoftwareSoftwareOSFinancials3Financials3FinancialsSpreadsheetsAccountingOracle中使用connectby来实现树状查询,其中可以使用level这个伪列来实现分层查询。具体使用如下:一张表menu记录菜单的层级情况。表结构如下:menu_idnumber,parent_idnumber,menu_namenvarchar2(20)首先select*frommenuconnectbymenu_id=parent_idstartwithmenu_id=1;这样可以看到Oracle以树状结构产生结果。某些时候如果我只想要第2层的菜单项如何做呢。select*from(selectlevel,menu_id,parent_id,menu_namefrommenuconncetbymenu_id=parent_idstartwithmenu_id=1)wherelevel=2这样就可以得到层级为第二层的菜单项。这样的SQL写法同样适合rownum伪列,Oracle中实现TOPn查询就是如此写的。
因篇幅问题不能全部显示,请点此查看更多更全内容