多級查詢在關于人事管理,如人員和部門、分公司關系,地區管理如:省、轄區、市、縣里面用到。當點開某一級,如何展開該級下所有數據。這種多層級查找,百度資料基本千篇一律,往往僅適用某一數據庫,如CTE僅適合sql server。幾番google,梳理各數據庫解決問題思路如下:
Oracle:
使用 CONNECT BY
Sql Server:
使用Common Table Expression (CTE)
【例如】:
部門表:id,name,parent_id
選擇某一部門時,該部門下所有子部門、子子部門全部遍歷出來。
with cte_child(id,name,parent_id) as (select id,name,parent_id from organization where id=50 union all select a.id,a.name,a.parent_id from organization a
inner join cte_child b on ( a.parent_id=b.id)) select * from cte_child;
mysql:
比較費勁,參考鏈接如下:
https://dba.stackexchange.com/questions/30021/mysql-tree-hierarchical-query