2017-07-14 87 views
0

我必須做出查詢來選擇父母的數據是SFI與ID 1然後刪除浴,破壞和分手SFI的孩子和淋浴盆,木地板,screeded休息的孩子。管理單列中的父子層次

表的結構。 (SOR表)

sor_id | items  | parent_id 
------------------------- 
1 | SFI   | 0 
2 | Remove bath | 1 
3 | Hack off | 1 
4 | break up | 1 
5 | Shower tray | 4 
6 | Timber floor| 4 
7 | screeded | 4 
8 | general 123 | 1 

所以我的問題是,我們可以使用自聯接兩次,在PHP一些鍛鍊環路,用於achieveing這樣的結果?

坦率地說,我不知道,我們可以管理這個層次有一個PARENT_ID,

select * from sor as m_sor 
LEFT JOIN sor as c_sor ON m_sor.sor_id = c_sor.parent_id 
LEFT JOIN sor as sc_sor 0N sc_sor.sor_id = c_sor.parent_id 
+0

零N?這不會工作 – Strawberry

+0

@Strawberry。抱歉。零N?我沒有明白你的意思。 – Bhavin

+1

好吧,仔細想想,然後再次閱讀您的查詢。很小心。 – Strawberry

回答

0

由於每@ RamRaider的指示MySQL不支持遞歸查詢。而且我無法更改表格結構。 所以我做了一個遞歸函數。 首先我選擇了數據庫中的所有數據並使用下面的recursive php函數。

function buildTree($ar, $pid = 0) { 
      $op = array(); 
      foreach($ar as $item) { 
       if($item['parent_id'] == $pid) { 
        $op[$item['sor_id']] = array(
         'sor_id' => $item['sor_id'], 
         'item_no' => $item['item_no'], 
         'price' => $item['price'], 
         'base_qty' => $item['base_qty'], 
         'description' => $item['description'], 
         'type' => $item['type'], 
         'form_name' => $item['form_name'], 
         'status' => $item['status'], 
         'modified_date' => $item['modified_date'], 
         'parent_id' => $item['parent_id'] 
        ); 
        // using recursion 
        $children = buildTree($ar, $item['sor_id']); 
        if($children) { 
         $op[$item['sor_id']]['children'] = $children; 
        } 
       } 
      } 
      return $op; 
} 

因此,它的工作,並返回給我想要的結果。