iT邦幫忙

3

想做部門階級

想做出集合結構:

總經辦
    資訊部
    管理
製造
    製一課
    制二課
    制三課
...

我做法是在C#那邊做邏輯處理
每個部門跑foreach去select一次
找到對應的部門跟單位

請問有一個select就可以解決的方法嗎?
我使用資料庫版本oracle

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
尼克
iT邦大師 1 級 ‧ 2018-03-19 11:53:45
最佳解答

Oracle PL/SQL: Treeview 樹狀查詢
HOW TO WORK WITH DOWNLINE HIERARCHIES IN ORACLE

Google 關鍵字 "oracle connect by" "oracle start with"

C# SMI iT邦新手 5 級 ‧ 2018-03-19 11:56:54 檢舉

謝謝大大

1

那就一次先全部select出來再處理,一般部門數了不起上千個,
一次select後處理是比較適合的作法。

C# SMI iT邦新手 5 級 ‧ 2018-03-19 10:32:45 檢舉

謝謝大大
假如沒有一次select組合方式,應該就用大大方法了

這要看你的表資料結構是什麼樣吧? 沒舉例很難知道適不適合這樣做?

3
暐翰
iT邦大師 1 級 ‧ 2018-03-19 13:01:07

尼克 大實作範例

-- ==== 測試資料 ====
-- 建立  Temp Table
commit; --Commit 後, 資料被刪除.
create Global Temporary table tom_tree(
  tree_id    number
, parent_id  number
, tree_name  varchar2(30)
);

-- 新增資料
insert into tom_tree values( 0, null, 'TOP' );
insert into tom_tree values( 1, 0, '總經辦' );
insert into tom_tree values( 2, 0, '製造' );
insert into tom_tree values( 3, 1, '資訊部' );
insert into tom_tree values( 4, 1, '管理部' );
insert into tom_tree values( 5, 2, '制一課' );
insert into tom_tree values( 6, 2, '制二課' );
insert into tom_tree values( 7, 2, '製三課' );

select * from tom_tree; --驗證資料是否正確

-- Treeview 查詢
select level 第幾階
     , tree_name
     , lpad( ' ', (Level - 1) * 3, ' ') || tree_name  as 結果
from tom_tree
start with parent_id is null
connect by prior tree_id = parent_id;

效率會高嗎? mysql適用嗎?

暐翰 iT邦大師 1 級 ‧ 2018-03-20 16:11:35 檢舉

效能可以
這是oracle版本,mysql要另外寫
可以參考 MySQL递归查询所有子节点,树形结构查询

我要發表回答

立即登入回答